Skip to content

Instantly share code, notes, and snippets.

@Alhadis
Created April 29, 2020 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alhadis/09c0fb11e6610801ff32e3335b348e96 to your computer and use it in GitHub Desktop.
Save Alhadis/09c0fb11e6610801ff32e3335b348e96 to your computer and use it in GitHub Desktop.
Balanced recursive match example
#!/usr/bin/env node
// Recursive match example
let input = `$(foo $(bar $(baz) qux) qul $(quz) 1) $(almost lisp`;
const matches = [];
const stack = [];
const {length} = input;
for(let i = 0; i < length; ++i){
let char = input[i];
let next = input[i + 1];
if("$" === char && "(" === next)
stack.push([i++, -1]);
else if(")" === char){
const match = stack.pop();
match[1] = i + 1;
matches.push(match);
}
}
console.log(matches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment