JSFiddle - React, Tailwind, and code Playground
HTML
Paste your code below, then hit this button → <input type="button" value="check my stack!" onclick="checkStack(document.querySelector('#checkit').value)"/>
<textarea id="checkit"></textarea>
CSS
#checkit {
height: 500px;
width: 90%;
background: #009;
color: #FF0;
font-family: monospace;
overflow: auto;
white-space: pre;
}
input[type=button] {
padding: 2px;
}
JavaScript
/**
* Does your code check out, stack wise?
* This simple script runs through your code,
* pushing and popping paired operators. It
* currently checks the following pairs, but
* if you can think of more pairs... add them?
*/
function checkStack(text)
{
// step one: strip comments. This is more work
// than you may think, thanks to quoted strings.
text = stripComments(text);
// opening characters for pairs
var openers = ["'",'"','{','[','('];
// closing characters for pairs
var closers = ["'",'"','}',']',')'];
// if we find a ' or ", we have to basically ignore everything
// until we find the closing character, because it's not code.
var exclusives = ["'",'"'];
// we're going to run through this text
// as Unicode. That's a problem for browsers
// that still implement Strings as sequences
// of bytes. Because bytes ruin everything.
var len = text.length,
c,
chr,
top,
op, // used for 'corresponding opener'
cl, // used for 'corresponding closer'
exclusively=-1, // there are some pairs that force us to ignore other characters
stack = [], // our pair stack (we'll only store openers)
lines = [], // our line-number-for-opening-operator
line=1,
error="Your stack was checked, and caught no flack!";
// let's go!
for(c=0; c<len; c++)
{
chr = text[c]; // JavaScript allows string-as-array access
// If we see an opening character, we chronicle this.
op = openers.indexOf(chr);
if(op!==-1 && exclusively===-1) {
window.console.log("[op] "+chr+", stack: ["+stack+"]");
push(stack,chr);
lines.push(line);
// check whether we need to go into 'exclusive' mode
exclusively = startExclusive(stack, exclusives, chr);
// This iteration is done. Don't waste cycles:
// move...