Last active
June 24, 2021 04:50
-
-
Save Gerst20051/0309e90edb4df110d879a2424429a287 to your computer and use it in GitHub Desktop.
Calculate Simple
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
const expression1 = '6+9-12'; | |
const expression2 = '1+2-3+4-5+6-7'; | |
const expression3 = '100+200+300'; | |
const expression4 = '1-2-3-0'; | |
const expression5 = '255'; | |
const expression6 = '0-1-2-3'; | |
function calculate(input) { | |
return reduceOperations(buildOperations(input)); | |
} | |
function buildOperations(input) { | |
const characters = input.split(''); | |
const operations = []; | |
let operation = []; | |
for (let characterIndex = 0; characterIndex < characters.length; characterIndex++) { | |
const character = characters[characterIndex]; | |
if (['+', '-'].includes(character)) { | |
operations.push(operation.join('')); | |
operations.push(character); | |
operation = []; | |
} else { | |
operation.push(character); | |
} | |
} | |
operations.push(operation.join('')); | |
return operations; | |
} | |
function reduceOperations(operations) { | |
return operations.slice(2).reduce((output, operation) => { | |
if (['+', '-'].includes(operation)) { | |
output.operator = operation; | |
} else { | |
if (output.operator === '+') { | |
output.result += parseInt(operation, 10); | |
} | |
if (output.operator === '-') { | |
output.result -= parseInt(operation, 10); | |
} | |
} | |
return output; | |
}, { | |
result: parseInt(operations[0], 10), | |
operator: operations[1], | |
}).result; | |
} | |
console.log(calculate(expression1) === 3); | |
console.log(calculate(expression2) === -2); | |
console.log(calculate(expression3) === 600); | |
console.log(calculate(expression4) === -4); | |
console.log(calculate(expression5) === 255); | |
console.log(calculate(expression6) === -6); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment