Created
September 14, 2020 05:13
-
-
Save peterlikesnoodles/1547420b18619c855c6765e666089e08 to your computer and use it in GitHub Desktop.
Evaluate expression with -, + and *.
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 eva = (str) => add(str) | |
const add = str => str.split('+').reduce((total, exp) => { | |
const s = exp.trim() | |
const num = Number(s) | |
return total + (isNaN(num) ? subtract(s) : num) | |
}, 0) | |
const subtract = str => str.split('-').reduce((total, exp, index) => { | |
const s = exp.trim() | |
const num = Number(s) | |
const result = isNaN(num) ? multiply(s) : num | |
return index ? total - result : result | |
}, 0) | |
const multiply = str => str.split('*').reduce((total, exp) => total * Number(exp.trim()), 1) | |
const check = fn => (param, expected) => { | |
const result = fn(param) | |
const pass = result === expected | |
console.log('[testing]', param, '<expected>', expected, pass ? '√' : `x - ${result}`) | |
} | |
const print = check(eva) | |
print('1 + 2', 3) | |
print('1 - 2', -1) | |
print('2 * 3', 6) | |
print('0 * 3', 0) | |
print('-1 + 3', 2) | |
print('-1 - 4', -5) | |
print('-2 * 4', -8) | |
print('-2 * 4 + 3', -5) | |
print('-2 * 4+ 3', -5) | |
print('-2* 4+ 3', -5) | |
print('-2*4 +3', -5) | |
print('1 - 2 * 4', -7) | |
print('5 +2 * 4', 13) | |
print(' 4 - 2 * 4 + 3', -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment