Currying is an advanced technique of working with functions. It’s used not only in JavaScript, but in other languages as well.
Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).
Currying doesn’t call a function. It just transforms it.
https://javascript.info/currying-partials
As you can see, the implementation is straightforward: it’s just two wrappers.
The result of curry(func) is a wrapper function(a).
When it is called like curriedSum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
Then this wrapper is called with 2 as an argument, and it passes the call to the original sum.
Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This technique can be useful for making code written in a functional style easier to read and compose. It's important to note that for a function to be curried, it needs to start out as one function, then broken out into a sequence of functions that each accepts one parameter.
// here ...args collects arguments as array (rest)
// Here we check if current args passed equals the number of args func expects
// if yes, we spread args elements to pass into func (spread). This is our base case.
/* if not, we return a function that collects the next arguments passed in next and we recursively call curriedFunc, accumalating and spreading the values of args first and then the values of next. next will take into consideration a variable amount of next arguments e.g (1, 2) (1) (1,2,3) */
function curry(func){
return function curriedFunc(...args){
if(args.length>=func.length){
return func(...args)
}else{
return function(...next){
return curriedFunc(...args,...next);
}
}
}
}
const join=(a,b,c)=>{return`${a}_${b}_${c}`}
const curriedJoin=curry(join)
curriedJoin(1, 2, 3) // '1_2_3'
curriedJoin(1)(2, 3) // '1_2_3'
curriedJoin(1,2)(3)// '1_2_3'
function curry(func){
return function curried(...args){
const complete=args.length>=func.length
&&!args.slice(0,func.length).includes(curry.placeholder);
if(complete) return func.apply(this,args)
return function(...newArgs){
// replace placeholders in args with values from newArgs
const res=args.map(arg=>arg===curry.placeholder&&newArgs.length?newArgs.shift():arg);
return curried(...res,...newArgs);
}
}
}
curry.placeholder=Symbol()
Function: length
The length data property of a Function instance indicates the number of parameters expected by the function.
function curry(fn){
return function curryInner(...args){
if(args.length>=fn.length) return fn(...args);
return(...args2)=>curryInner(...args,...args2);
};
}
reference:https://cloud.tencent.com/developer/article/1431398
柯里化,又称部分求值,一个currying的函数首先会接受一些参数,接受这些部分参数后,函数并不会立即求值,而是继续返回另一个函数,部分参数在函数形成的闭包中被保存起来,待到函数被真正需要求值的时候,之前传入的所有参数都会被一次性用于求值。
柯里化的作用就是将普通函数转变成高阶函数,实现动态创建函数、延迟计算、参数复用等作用。
把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术。
fn(1, 2, 3, 4) -> fn(1)(2)(3)(4)()
假设这个函数是用于求和,那么就是把本来接收多个参数一次性求和的函数改成了接收单一参数逐个求和的函数,这样是不是容易理解了。
currying函数: 判断传入的参数长度是否为0,若为0执行函数,否则收集参数到args数组;另一种常见的应用是bind函数。
example1:
// 通用currying函数,接受一个参数fn(即要被currying的函数)
var currying = function(fn) {
var args = [];
return function curried() {
if (arguments.length === 0) {
return fn.apply(this, args);
} else {
[].push.apply(args, arguments);
return arguments.callee;
}
}
};
// 将被currying的函数
var cost = (function() {
var money = 0;
return function() {
for (var i = 0, l = arguments.length; i < l; i++) {
money += arguments[i];
}
return money;
}
})();
var cost = currying( cost ); // 转化成currying函数
cost( 100 ); // 未真正求值
cost( 200 ); // 未真正求值
cost( 300 ); // 未真正求值
console.log (cost()); // 求值并输出:600
example2:
实现上就是返回一个高阶函数,通过闭包把传入的参数保存起来。当传入的参数数量不足时,递归调用bind方法;数量足够时则立即执行函数。
function curry(fn){
const len=fn.length;
return function curried(...args){
if(args.length<len){
return curried.bind(null,...args);
}
return fn.apply(null,args);
}
}
ES6极简写法
const currying = fn =>
curried = (...args1) =>
args1.length>=fn.length
? fn(...args1)
: (...args2) => curried(...args1,...args2)
fn.length表示函数的所有参数个数吗?不是,函数的length属性获取的是形参的个数
如果很难理解,看下面例子:
function currying(fn,length){
length=length || fn.length;
return function(...args){
return args.length>=length
?fn.apply(this,args)
:currying(fn.bind(this,...args),length-args.length)
}
}
JS的API哪些应用到了函数柯里化的实现?
实现一个sum函数,sum(1,2)(3).valueOf()这样调用后的结果为6
function sum(...rest){
let args= [...rest];
const f = function(...others){
args= args.concat(others);
return f;
};
f.valueOf = function() {
let result = 0;
for(let val of args) {
result += val;
}
return result;
}
return f;
}