# 一个关于柯里化函数的实现解析

JavaScript专题之函数柯里化

## 一个柯里化函数的实现

### 实现方式

``````function curry(fn, argLen, currArgs) {
return function() {
console.log("arguments:", arguments, arguments.length)
var args = [].slice.call(arguments);
console.log("args:", args)
// 首次调用时未提供最后一个参数
if (currArgs !== undefined) {
args = args.concat(currArgs);
}
// 递归出口
if (args.length == argLen) {
return fn.apply(this, args);
} else {
return curry(fn, argLen, args);
}
}
}

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

// 改造普通函数，返回柯里函数
var sum = curry(sumOf, 4);``````

#### sum(1,2,3,4)

``````>sum(1,2,3,4)
arguments: Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] 4
args: (4) [1, 2, 3, 4]
``````

#### sum(1,2,3)(4)

``````>sum(1,2,3)(4)
arguments: Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ] 3
args: (3) [1, 2, 3]
arguments: Arguments [4, callee: ƒ, Symbol(Symbol.iterator): ƒ] 1
args: [4]``````

#### sum(1,2)(3,4)

``````>sum(1,2)(3,4)
arguments: Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ] 2
args: (2) [1, 2]
arguments: Arguments(2) [3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] 2
args: (2) [3, 4]``````

#### 个人优化

``````function curry(fn, currArgs) {
return function() {
console.log("arguments:", arguments, arguments.length)
var args = [].slice.call(arguments);
console.log("args:", args)
// 首次调用时未提供最后一个参数
if (currArgs !== undefined) {
args = args.concat(currArgs);
}
// 递归出口
if (args.length == fn.length) {
return fn.apply(this, args);
} else {
return curry(fn, args);
}
}
}``````

## 小结

``````var persons = [{name: 'kevin', age: 11}, {name: 'daisy', age: 24}]

let getProp = _.curry(function (key, obj) {
return obj[key]
});
let names2 = persons.map(getProp('name'))
console.log(names2); //['kevin', 'daisy']

let ages2 = persons.map(getProp('age'))
console.log(ages2); //[11,24]``````

1.6k 声望743 粉丝

0 条评论