Home > Article > Web Front-end > Ideas and source code for implementing curry function in JavaScript
This article brings you the ideas and source code for implementing curry functions in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Implementation effect
const curry_fn = curry(fn); fn(1, 2, 3) == curry_fn(1)(2)(3);
Storage incoming parameters through closure
Obtain the number of parameters through the length attribute of the function
When the number of parameters is not enough, the method directly returns the number of parameters stored
Execute the original function when the number of parameters is equal to the original function
If you use the ES6 parameter default value, length will not be equal to the actual number of parameters
Parameters are obtained from arguments, and ES6 directly uses rest parameters to implement
function curry(fn) { var length = fn.length; //获取原函数的参数个数 var args = []; // args存储传入参数 return function curryFn() { // 将arguments转换成数组 var curryArgs = Array.prototype.slice.call(arguments); args = args.concat(curryArgs); if (args.length > length) { throw new Error('arguments length error') } // 存储的参数个数等于原函数参数个数时执行原函数 if (args.length === length) { return fn.apply(null, args); } // 否则继续返回函数 return curryFn; }; }
function curry(fn) { let length = fn.length; let args = []; return function curryFn(...curryArgs) { args = args.concat(curryArgs); if (args.length > length) { throw new Error('arguments length error') } if (args.length === length) { return fn(...args); } return curryFn; } }
The above is the detailed content of Ideas and source code for implementing curry function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!