Created
June 29, 2020 17:57
-
-
Save bt4R9/e4ef9fc1b64efbfd2d7c7418eff1da15 to your computer and use it in GitHub Desktop.
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 parse(input) { | |
input = input.split(''); | |
const stack = []; | |
const isChar = (char) => /[a-z]/.test(char); | |
const isNum = (char) => /[0-9]/.test(char); | |
for (const char of input) { | |
if (char === '[') { | |
stack.push(char); | |
} else if (isChar(char)) { | |
stack.push(char); | |
} else if (isNum(char)) { | |
stack.push(char); | |
} else if (char === ']') { | |
const slice = []; | |
while (stack[stack.length - 1] !== '[') { | |
slice.unshift(stack.pop()); | |
} | |
stack.pop(); | |
if (isNum(stack[stack.length - 1])) { | |
const num = stack.pop(); | |
for (let i = 0; i < num; i++) { | |
stack.push(...slice); | |
} | |
} else { | |
stack.push(...slice); | |
} | |
} | |
} | |
return stack.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment