Skip to content

Instantly share code, notes, and snippets.

@bt4R9
Created June 29, 2020 17:57
Show Gist options
  • Save bt4R9/e4ef9fc1b64efbfd2d7c7418eff1da15 to your computer and use it in GitHub Desktop.
Save bt4R9/e4ef9fc1b64efbfd2d7c7418eff1da15 to your computer and use it in GitHub Desktop.
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