Created
September 21, 2016 18:46
-
-
Save sgnl/7771e70380d819fdb827d94514a8ab9f to your computer and use it in GitHub Desktop.
Curry Calculator
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
// https://repl.it/Ccki/2 | |
function calculator(num) { | |
var equation = []; | |
function captureNumber (num) { | |
equation.push(num); | |
return captureOperator; | |
} | |
function captureOperator(op) { | |
if (op === '=') { | |
return processEquation(equation); | |
} | |
equation.push(op); | |
return captureNumber; | |
} | |
function processEquation(eqArr) { | |
var lastNumSeen = null; | |
var lastOpSeen = null; | |
return eqArr.reduce(function(sum, curr, index){ | |
if (!index) return sum + curr; | |
if (typeof(curr) === 'number') { | |
switch(lastOpSeen) { | |
case '+': return sum + curr; | |
case '-': return sum - curr; | |
default: console.log('defaulted', curr); | |
} | |
lastOpSeen = null; | |
return sum; | |
} | |
if (typeof(curr) === 'string') { | |
lastOpSeen = curr; | |
return sum; | |
} | |
}, 0); | |
} | |
return captureNumber(num); | |
} | |
// code commented out is equivalent to line 59 | |
// var getNextOp = calculator(1); | |
// var getNextNum = getNextOp('+'); | |
// getNextOp = getNextNum(1); | |
// getNextNum = getNextOp('-'); | |
// getNextOp = getNextNum(1); | |
// getNextNum = getNextOp('+'); | |
// getNextOp = getNextNum(10); | |
// var result = getNextOp('='); | |
var result = calculator(5)('+')(1)('-')(1)('+')(10)('='); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment