每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
函数柯里化 了解一下?
// 固定参数实现
const result = x => y => z => x * y * z;
result(3)(4)(4) // 48;
// 柯里化实现
function curry(fn) {
const len = fn.length;
return function curried() {
const args = Array.prototype.slice.call(arguments);
if (args.length >= len) {
return fn.apply(this, args);
}
return function () {
return curried.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
const result = curry(function (a, b, c) {
return a * b * c;
});
result(3)(4)(4); // 48
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。// es6
const mul = (x) => {
let sum = x
let curried = (y) => {
sum = sum * y
return curried
}
curried.toString = () => sum
return curried
}
console.log(mul(1)) //1
console.log(mul(1)(2))//2
console.log(mul(1)(2)(3))//6
console.log(mul(1)(2)(3)(4))//24
...
// es5
function mul(x){
var sum = x
var curried = function(y){
sum = sum * y
return curried
}
curried.toString=function(){
return sum
}
return curried
}
console.log(mul(1)) //1
console.log(mul(1)(2))//2
console.log(mul(1)(2)(3))//6
console.log(mul(1)(2)(3)(4))//24
...
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。例如
multiply(3,4,4) 转为 multiply(3)(4)(4)
将一个普通的多参数定义,如
function multiply(a,b,c){
return a*b*c
}
转为单参数函数多次调用
function multiply(a){
return function(b){
return function(c){
return a*b*c
}
}
}
使用ES6的写法就是
const multiply = a=>b=>c=>a*b*c
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。Function Currying
function curry(fn, ...args){
return args.length === fn.length ?
fn(...args) :
(...next_args) => curry(fn, ...args, ...next_args);
}
function mul(a, b, c){
return a * b * c;
}
// mul(3, 4, 4); => 48
let a = curry(mul);
a(3)(4)(4);
// => 48
a(3, 4, 4);
// => 48
a(3)(4, 4);
// => 48
a()()()()()(3, 4)(4);
// => 48
// 来晚了 ...
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。const a = x => Object.assign(
y => a(x * y),
{
valueOf: () => x,
toString: () => String(x),
}
)
a(3)(4)(4) == 48 // ==> true
String(a(3)(4)(4)) // ==> "48"
console.log(a(3)(4)(4)) // ==> f 48
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。固定3个参数的的柯里化。。。
const curry3 = fn=> a => b => c => fn(a,b,c);
const mutl3 = (a, b, c) => a * b * c;
const curried3 = curry3(mutl3);
let result = curried3(3)(4)(4);
console.log(result);
如果是更加通用的累乘,参数不定,就不能这么用了。
const curry = fn => {
let _args = [];
const _fn = (...args) => {
_args.push(...args);
return args.length >= 1 ? _fn : fn(..._args);
}
return _fn;
}
// 累乘
const multiplication = curry(function() {
return Array.prototype.reduce.call(arguments, (acc, val) => {
return acc * val;
}, 1);
});
let result = multiplication(3)(4)(4)();
console.log(result);
**bold**
_italic_
[link](http://example.com)
> 引用
`code`
-
列表
。关闭理由: 删除理由: 忽略理由:
补充说明:
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
看到这问题就想到柯里化,这个小代码写的也挺有意思的。
— 七月 · 3月30日