Skip to content

Instantly share code, notes, and snippets.

@maniart
Last active November 11, 2021 16:05
Show Gist options
  • Save maniart/25a7a0939d0958c422c7 to your computer and use it in GitHub Desktop.
Save maniart/25a7a0939d0958c422c7 to your computer and use it in GitHub Desktop.
Infinite Curry
/*
Implement a function that allows for infinite cyrring, and can be used as such:
`_do(fn)(2)(3)(5)(8)(22)(230)(100)(10)();`
*/
function _do(fn) {
var args = []
, fn;
function exec() {
return args.reduce(function(prev, curr) {
return fn && fn.call(null, prev, curr);
});
}
function addArg(arg) {
if(arg) {
args.push(arg);
console.log('got another arg! all args: ', args);
return addArg;
} else {
console.log('time to exec!');
return exec();
}
}
if(arguments.length < 1) {
console.log('returning _do');
return _do;
} else {
console.log('got fn ', fn);
fn = arguments[0];
return addArg;
}
}
//Sample use case:
function add(num1, num2) {
return num1 + num2;
}
_do(add)(2)(3)(5)(8)(22)(230)(100)(10)();
// or to log: console.log(_do(add)(2)(3)(5)(8)(22)(230)(100)(10)());
@peteromano
Copy link

function curry(fn, seed) {
      var values = [], slice = Array.prototype.slice;
      return function curry() {
        if(arguments.length) {
              values = values.concat(slice.call(arguments));
              return curry;
          } else {
              return fn ? values.reduce(fn, seed || 0) : seed;
          }
      }
}

(function(seed) {
  var add = curry( function(num1, num2) { return num1 + num2; }, seed );
  return add(2)(3)(5, 50)(10, 15, 5)();
})(10); // 100

// Or a more practical example (without hardcoded values):

(function(data, seed) {
  var add = curry( function(num1, num2) { return num1 + num2; }, seed );
  for(var value in data) add.apply(null, [].concat(data[value]));
  return add();
})(
  // data
  [ 2, 3, [5, 50], [10, 15, 5] ],
  // seed
  10
); // 100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment