JSFiddle - React, Tailwind, and code Playground

by webchemist

HTML

<input type="button" value="timer" /> state: <span id="latch"></span> | <span id="s">s</span> | <span id="r">r</span><br/>
<code>
<div id="numbers"></div>
</code>

JavaScript

function leadingZeros(digits, value)
{
    while(value.length < digits)
        value = "0" + value;
    
    return value;
}

function srLatch(s, r)
{
    $("#s").text(s);
    $("#r").text(r);
    if(s == 0 && r == 0) return;
    if(s == 0 && r == 1){
        $("#latch").text("reset (down)");
        return countUp = false;
    }
    if(s == 1 && r == 0)
    {
        $("#latch").text("set (up)");
        return countUp = true;
    }
    if(s == 1 && r == 1)
        $("#latch").text("undetermined value");
}

function nand(x, y)
{
    return (x == 1 && y == 1) ? 0 : 1;
}

function stepCounter()
{
    var num = leadingZeros(4, startInt.toString(2));
    
    // these are swapped due to string indexing left to right
    // so charAt 0 is the Q3 MSB, and charAt 3 is Q0 LSB
    q3 = num.charAt(0);
    q2 = num.charAt(1);
    q1 = num.charAt(2);
    q0 = num.charAt(3);
    
    // got it down to 5 nands - 2 for the SR latch
    
    // nand(a,a) is inverting Q0 and feeds into set, 
    // so for 0-7 its putting a 1 on S
    
    // nand(a,b) is nand of (Q3, Q2) so its 1 until it hits c and 11xx
    // makes the nand false. 
    var q3_2 = nand(q3,q2);
    
    //The nand (ab,ab) inverts it back as if it were an and()
    srLatch(nand(q3,q3),nand(q3_2,q3_2));
    
    startInt += (countUp) ? 1 : -1;
    if(startInt == -1) startInt = 15;
    startInt %= 16;
    $("#numbers").children().css("color","black");
    $("#_"+startInt).css("color","red");
    
}
function toggleTimer(){
    if(timer == null)
        timer = window.setInterval(function () {stepCounter()}, 1000);    
    else{
        window.clearInterval(timer);
        timer = null;
    }
}

var countUp = true;
var startInt = -1;
var timer;

$('input').click(function(){toggleTimer()});

for (i = 0; i < 16; i++)
{
    var num = Number(i).toString(2);
    $("#numbers").append($('<div>').attr('id',"_"+i)
                 .text(i.toString(16)+" "+leadingZeros(4, num)));   
}