const operations = {
addition(p1, p2) {
//console.log(p1, p2, 'addition operation');
return p1 + p2;
},
subtraction(p1, p2) {
//console.log(p1, p2, 'subtr operation');
return p1 - p2;
}
,
multiplication(p1, p2) {
//console.log(p1, p2, 'multi operation');
return p1 * p2;
},
absoluteValue(p1) {
return Math.abs(p1);
}
}
function calculate(commands) {
commands = commands.replaceAll(' ', '');
const regex = /(multiplication|addition|subtraction)\(-?\d+,-?\d+\)/g;
const regexAbsolute = /absoluteValue\(-?\d+\)/g;
while (!/^\d+$/g.test(commands)) {
console.log(commands);
let match = commands.match(regex);
if (match === null) {
match = commands.match(regexAbsolute);
}
match = [...match][0];
const indexOfParenthesis = match.indexOf('(');
const operationType = match.substring(0, indexOfParenthesis);
if (operationType in operations) {
const parameters = [...match.matchAll(/\((.*)\)$/g)][0][1].split(',');
//console.log(parameters, match, 'params');
const value = operations[operationType].apply(null, parameters.map(p => parseInt(p)));
commands = commands.replace(match, value);
} else {
throw new Error('something gone wrong');
}
}
return commands;
}
console.log(calculate('absoluteValue(addition(addition(16296,78),subtraction(multiplication(-1,5263),40)))'));