Created
October 17, 2021 18:41
-
-
Save lior-amsalem/06762c90f62e8a6a1db02f32c10047fe to your computer and use it in GitHub Desktop.
Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression. see example below
This file contains hidden or 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
/** | |
Example: | |
Calculator().evaluate("2 / 2 + 3 * 4 - 6") # => 7 | |
**/ | |
const Calculator = function() { | |
this.resolveMultiDivision = mathString => { | |
var resolvedTop = mathString.replace(new RegExp(/(\d*\.?\d*)([\/\*])(\d*\.?\d*)/), (match, group1,group2,group3) => { | |
return group2 === '*' ? group1 * group3 : group1 / group3; | |
}); | |
let hasMoreToResolve = !!resolvedTop.match(/[/\/*]/g); | |
if(hasMoreToResolve) { | |
return this.resolveMultiDivision(resolvedTop); | |
} | |
return this.resolveSubAndAdd(resolvedTop); | |
} | |
this.resolveSubAndAdd = mathString => { | |
console.log('resolveSubAndAdd', mathString) | |
var resolvedTop = mathString.replace(new RegExp(/(\d*\.?\d*)([\-\+])(\d*\.?\d*)/), (match, group1,group2,group3) => { | |
return group2 === '+' ? Number(group1) + Number(group3) : Number(group1) - Number(group3); | |
}); | |
let hasMoreToResolve = !!resolvedTop.match(/[-+]/g); | |
if(hasMoreToResolve) { | |
return this.resolveSubAndAdd(resolvedTop); | |
} | |
return resolvedTop; | |
} | |
this.evaluate = string => { | |
let nospace = string.replace(/ /gi,''); | |
return this.resolveMultiDivision(nospace); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment