函数柯理化是什么,手动实现一个柯理化函数

函数柯理化

  • 原理:函数柯理化的本质就是将函数接受的多个参数单一化,并且返回接受余下的参数且返回结果的新函数的一种技术。

简单版求和

1
2
3
4
5
6
7
8
function add (a) {
return function (b) {
return function (c) {
return a + b + c
}
}
}
console.log(add(1)(2)(3)) // 6

函数柯理化

  • 参数长度固定
1
2
3
4
5
6
7
8
9
10
const curry = (fn) =>
(judge = (...args) =>
args.length === fn.length
? fn(...args)
: (...arg) => judge(...args, ...arg));
const add = (a, b, c) => a + b + c;
const curryAdd = curry(add);
console.log(curryAdd(1)(2)(3)); // 6
console.log(curryAdd(1, 2)(3)); // 6
console.log(curryAdd(1)(2, 3)); // 6
  • 参数长度不固定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function add (...args) {
args.reduce((a, b) => a + b)
}
function currying (fn) {
let args = []
return function temp (...newArgs) {
if (newArgs.length) {
args = [
...args,
...newArgs
]
return temp
} else {
let val = fn.apply(this, args)
args = []
return val
}
}
}
let addCurry = currying(add)
console.log(addCurry(1)(2)(3)) // 6

that’s all!

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信