Created
February 25, 2018 02:44
-
-
Save codyromano/6246572a631daf3fc31f7fdfd65c39e9 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
const getCalculateRegex = operator => new RegExp( | |
'([0-9]+) ?\\' + operator + ' ?([0-9]+)', 'ig' | |
); | |
const operations = [ | |
{ operator: '*', fn: (n1, n2) => n1 * n2 }, | |
{ operator: '/', fn: (n1, n2) => n1 / n2 }, | |
{ operator: '+', fn: (n1, n2) => n1 + n2 }, | |
{ operator: '-', fn: (n1, n2) => n1 - n2 } | |
]; | |
function calculate(inputString) { | |
let result = inputString; | |
operations.forEach(({ operator, fn }) => { | |
const regex = getCalculateRegex(operator); | |
result = result.replace(regex, (_, n1, n2) => fn( | |
...[n1, n2].map(parseFloat) | |
)); | |
}); | |
return parseFloat(result); | |
} | |
console.assert(calculate('2 + 2') === 4, 'Add'); | |
console.assert(calculate('10 / 5') === 2, 'Divide'); | |
console.assert(calculate('3 * 2') === 6, 'Multiply'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment