Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Last active June 24, 2021 04:51
Show Gist options
  • Save Gerst20051/e87db3da15b26014fb768ddef450a73a to your computer and use it in GitHub Desktop.
Save Gerst20051/e87db3da15b26014fb768ddef450a73a to your computer and use it in GitHub Desktop.
Calc JS Function
// TODO: finish
function calc(input) {
const characters = input.split(''); // ['(', '1', '+', '2', ')']
let depth = 0;
const operations = []; // ['1', '+', '2']
let calculation = [];
for (let characterIndex = 0; characterIndex < characters.length; characterIndex++) {
const character = characters[characterIndex];
if (character === '(') {
depth++;
} else if (character === ')') {
if (characterIndex <= characters.length - 1 && depth > 0) {
// operations.push(calculation[depth - 1]);
}
operations.push(calculation[depth]);
calculation[depth] = [];
depth--;
} else {
if (calculation[depth]) {
calculation[depth].push(character);
} else {
calculation[depth] = [character];
}
}
}
console.log(input, operations);
const filteredOperations = operations.filter(op => op);
const result = filteredOperations.reduce((output, operation) => {
if (!operation) return output;
if (operation[1] === '+') {
return output + parseInt(operation[2], 0);
}
if (operation[1] === '*') {
return output * parseInt(operation[2], 0);
}
return output;
}, parseInt(filteredOperations[0][0], 0));
console.log(input, result);
return result;
}
console.log(calc('(1+2)') === 3);
console.log(calc('(4*6)') === 24);
console.log(calc('((1+2)*(4+4))') === 24);
console.log(calc('(5+(7*3))') === 26);
console.log(calc('(((5+(4*3))*2)+1)') === 35);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment