什么时候函数的实际 .length 不足以满足 _.curry()
When would a function's actual .length be insufficient for _.curry()
我 运行 遇到了一个奇怪的情况,在 a 上使用 _.curry
的函数立即调用了该函数。阅读 lodash 文档后,我们发现我们需要声明 arity,这要感谢写得很好的文档:
The arity of func may be specified if func.length is not sufficient.
但是,我很好奇是否有人知道为什么会发生这种情况的任何实际示例(不一定是它在我的代码库中发生的具体原因)。
However, I'm curious if anyone knows any actual examples of why this might happen (not necessarily the specific reason it happened in my codebase).
示例:
- 该函数使用
arguments
对象而不是形式参数:
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i += 1) {
total += arguments[i];
}
return total;
}
console.log('length', sum.length); // 0
console.log('result', sum(3, 4));
- 该函数使用了一个 "rest" 参数:
function sum(...values) {
return values.reduce((a, v) => a + v, 0);
}
console.log('length', sum.length); // 0
console.log('result', sum(3, 4));
- 函数已被部分计算或已进行了一些其他转换:
function add(x, y) { return x + y; }
var inc = _.partial(add, 1);
console.log('add length', add.length); // 2
console.log('inc length', inc.length); // 0
console.log('result', inc(8));
var squarePlusOne = _.flow(x => x * x, x => x + 1);
console.log('length', squarePlusOne.length); // 0
console.log('result', squarePlusOne(7));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
- 该函数的参数多于您实际想要柯里化的参数(即它具有可选参数)
function combine(x, y, z) {
return x + y + (z || 0);
}
console.log('length', combine.length); // 3
console.log('result', combine(3, 4));
我 运行 遇到了一个奇怪的情况,在 a 上使用 _.curry
的函数立即调用了该函数。阅读 lodash 文档后,我们发现我们需要声明 arity,这要感谢写得很好的文档:
The arity of func may be specified if func.length is not sufficient.
但是,我很好奇是否有人知道为什么会发生这种情况的任何实际示例(不一定是它在我的代码库中发生的具体原因)。
However, I'm curious if anyone knows any actual examples of why this might happen (not necessarily the specific reason it happened in my codebase).
示例:
- 该函数使用
arguments
对象而不是形式参数:
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i += 1) {
total += arguments[i];
}
return total;
}
console.log('length', sum.length); // 0
console.log('result', sum(3, 4));
- 该函数使用了一个 "rest" 参数:
function sum(...values) {
return values.reduce((a, v) => a + v, 0);
}
console.log('length', sum.length); // 0
console.log('result', sum(3, 4));
- 函数已被部分计算或已进行了一些其他转换:
function add(x, y) { return x + y; }
var inc = _.partial(add, 1);
console.log('add length', add.length); // 2
console.log('inc length', inc.length); // 0
console.log('result', inc(8));
var squarePlusOne = _.flow(x => x * x, x => x + 1);
console.log('length', squarePlusOne.length); // 0
console.log('result', squarePlusOne(7));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
- 该函数的参数多于您实际想要柯里化的参数(即它具有可选参数)
function combine(x, y, z) {
return x + y + (z || 0);
}
console.log('length', combine.length); // 3
console.log('result', combine(3, 4));