Circuits that remember
Gates forget: change the input and the output changes. Wire two gates in a loop and the circuit holds its state — a latch. Add a clock — a signal ticking 0,1,0,1 billions of times a second — and you get a flip-flop that only listens at the moment the clock rises. A row of them is a register.
Edges, not levels
A camera with a shutter: the scene keeps changing, but the photo only captures the instant the button goes down. The rising clock edge is the button.
function makeRegister(bits) {
const mask = 2 ** bits - 1;
let value = 0;
let lastClock = 0;
return {
tick(clock, load, d) {
if (clock === 1 && lastClock === 0 && load === 1) value = d & mask;
lastClock = clock;
},
get value() {
return value;
},
};
}
function makeCounter(bits) {
const size = 2 ** bits;
let value = 0;
let lastClock = 0;
return {
tick(clock, reset) {
if (clock === 1 && lastClock === 0) value = reset === 1 ? 0 : (value + 1) % size;
lastClock = clock;
},
get value() {
return value;
},
};
}