Created
December 12, 2018 13:30
-
-
Save quisido/08341ee42b8431cc4b4e010c397555eb to your computer and use it in GitHub Desktop.
Variable length currying in JavaScript
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
// Given an array of numbers, if the index is even, add. | |
// If the index is odd, subtract. | |
const addSubtractReducer = (total, current, index) => | |
(index % 2) === 0 ? | |
total + current : | |
total - current; | |
const addSubtract = x => { | |
const nums = [ ]; | |
// Recursive function that accumulates numbers for the operation. | |
const f = y => { | |
nums.push(y); | |
return f; | |
}; | |
// When the recursive function is type cast to a number, | |
// reduce the accumulated numbers. | |
f.valueOf = () => { | |
return nums.reduce(addSubtractReducer, x); | |
}; | |
// Return the recursive function, having added the first digit. | |
return f; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment