Logic gates via closures in JavaScript. Inspired by nand2tetris.
npm install --save-dev g8
g8 is a standalone library offering just a handful of common logic gates that can be used as building blocks to implement more complex systems, such as the Nu CPU and the Mu computer.
// Import g8
var g8 = require('g8');
// Compute a simple boolean AND.
console.log( g8.and('000', '111') ); // Console 000
// Compute a simple boolean OR.
console.log( g8.or('101', '010') ); // Console 111
// Create a 6-bit word register.
var word = g8.word(6);
// Store 42.
console.log( word('101010', '1') ); // Log 101010
// Create a 6-bit word register of 2 cells.
var cluster = g8.cluster(6, 2);
// Store 15 in @0 and 63 in @1.
console.log( cluster('101010', '0', '1') ); // Log 101010
console.log( cluster('111111', '1', '1') ); // Log 111111
// Retrieve @0 and @1
console.log( cluster('000000', '0', '0') ); // Log 101010
console.log( cluster('000000', '1', '0') ); // Log 111111
Latches are toggle switches whose outputs are fed to itself. This behavior causes the latch to keep its state. The inverted SR latch implemented in the library is just one of several. If set is 0, the output will be latched to 1, and the circuit will continue to output 1 unless reset is set instead, which latches the output to 0. The latch is therefore a very simple form of memory.
Data flip flops add a second level of nand gates to a SR latch inverting its set / reset inputs and a control bit to enable / disable the circuit. The control bit is usually an oscillating clock signal, carefully calibrated to synchronize faster circuits with slower ones. The result is that circuits keep their previous state while the clock is down giving slower circuits time to catch up with the faster ones. Circuits maintain their state ignoring any invalid data until the system stabilizes.
For a more thorough and robust explanation refer to the third chapter of The Elements of Computing Science and see the section titled Time Matters.
Every register in a memory cluster is read, but only one is written. Voltage variations in the real world propagate almost instantaneously, whereas every cell of an array must be addressed in the simulation. In order to keep one's sanity leave turbo mode enabled by default, but try setting it to false if you feel unhurried.
Due to physical constraints, real world sequential circuits operate at different speeds. Clock signals are used to synchronize these systems. Circuits here execute orderly, and auto-feeback is done via closures. A multi-threaded simulation running several interdependent circuits asynchronously could use this flag to syncronize the system.
- nand2tetris.org
- NAND Logic
- Implementing NAND Gates
- Combinational Logic
- Sequential Logic
- Crystal Oscillator
- Clock Rate
MIT © Jorge Bucaran