Created
April 29, 2020 17:26
-
-
Save Alhadis/09c0fb11e6610801ff32e3335b348e96 to your computer and use it in GitHub Desktop.
Balanced recursive match example
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
#!/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