Skip to content

Instantly share code, notes, and snippets.

@codyromano
Created February 25, 2018 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyromano/6246572a631daf3fc31f7fdfd65c39e9 to your computer and use it in GitHub Desktop.
Save codyromano/6246572a631daf3fc31f7fdfd65c39e9 to your computer and use it in GitHub Desktop.
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