Skip to content

Instantly share code, notes, and snippets.

@quisido
Created December 12, 2018 13:30
Show Gist options
  • Save quisido/08341ee42b8431cc4b4e010c397555eb to your computer and use it in GitHub Desktop.
Save quisido/08341ee42b8431cc4b4e010c397555eb to your computer and use it in GitHub Desktop.
Variable length currying in JavaScript
// 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