xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js currying function All In One

js 实现 (5).add(3).minus(2) 功能

例: 5 + 3 - 2,结果为 6



https://stackoverflow.com/questions/36314/what-is-currying

1. normal function

function add (a, b) {
  return a + b;
}

add(3, 4); 
// 7

2. currying function

function add (a) {
  return function (b) {
    return a + b;
  }
}

add(3)(4);
// 7

// OR
var add3 = add(3);
// f()
add3(4);
// 7

自适应参数长度的 curry 函数 ✅

https://javascript.info/currying-partials


function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  };
}

demos

const log = console.log;

function sum(a, b, c) {
  return a + b + c;
}

const curriedSum = curry(sum);

log( curriedSum(1, 2, 3) );
 // 6, still callable normally

log( curriedSum(1)(2,3) ); 
// 6, currying of 1st arg

log( curriedSum(1)(2)(3) );
 // 6, full currying

refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/12728760.html