Created
October 31, 2011 15:03
-
-
Save rctay/1327679 to your computer and use it in GitHub Desktop.
[js] 2-bit counter with JK flip-flops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function flip(bit) { | |
return bit ? 0 : 1; | |
} | |
// each call simulates clock tick | |
function jk() { | |
var q=0; | |
return function(j, k) { | |
if (j) { | |
if (k) | |
// // Q(t+1) = ~Q(t)) | |
return (q = flip(q)); | |
else | |
// // Q(t+1) = 1 | |
return (q = 1); | |
} else { | |
if (k) | |
// // Q(t+1) = 0 | |
return (q = 0); | |
else | |
// Q(t+1) = Q(t) | |
return q; | |
} | |
}; | |
} | |
/* | |
* JK-flip flop demo - 2-bit counter | |
* each call simulates clock tick | |
* sample run: | |
* > c1 = counter() | |
* => [Function] | |
* > c1() | |
* => [ 0, 0 ] | |
* > c1() | |
* => [ 0, 1 ] | |
* > c1() | |
* => [ 1, 0 ] | |
* > c1() | |
* => [ 1, 1 ] | |
* > c1() | |
* => [ 0, 0 ] | |
*/ | |
function counter() { | |
var ff1=jk(); //MSB | |
var ff0=jk(); //LSB | |
var a1 = 0, a0 = 0; | |
return function() { | |
var r = [a1, a0]; | |
a1 = ff1(a0, a0); | |
a0 = ff0(1, 1); | |
return r; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment