dma*_*man 0 javascript currying
我是新来的咖喱功能,有人建议我使用它们.我想知道这个:
var updateNodeStorage;
updateNodeStorage = function(devicesToCheck) {
var nodesToCallOut;
nodesToCallOut = devicesToCheck.filter(function(device) {
var nodeExistInStorage;
return nodeExistInStorage = nodeStorage.devices.every(function(nodeInStorage) {
return device.id !== nodeInStorage.id;
});
});
nodesToCallOut.forEach(function(node) {
getNodeProtocol(node.id);
});
};
Run Code Online (Sandbox Code Playgroud)
为此代码使用咖喱函数是否有益?如果是这样,我将在何处以及如何使用它?
不,我没有看到代码currying有用的任何地方.
Currying是预先填充函数的一个或多个参数(有时称为"部分应用"函数)的做法,因此稍后当调用curried函数时,这些参数将传递给原始函数.这是一个例子:
// A boring function
function foo(a, b) {
snippet.log("a = " + a + ", b = " + b);
}
// Create one curried with the value 1 for a using Function#bind
var curriedFoo1 = foo.bind(null, 1);
// Call it
curriedFoo1(2); // "a = 1, b = 2"Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
正如您在上面所看到的,JavaScript Function#bind可以用于curry,但是它还有一个问题,它也设置了所使用的值this(这就是上面null作为第一个参数传递的原因bind).虽然很容易添加一个,但JavaScript没有内置的只是干扰而不会搞乱this的方法.(例如,PrototypeJS Function#curry为函数添加了一个.)
这是一个未经优化的纯粹curry:
if (!Function.prototype.curry) {
(function() {
var slice = Array.prototype.slice;
Function.prototype.curry = function() {
var curriedArgs = slice.call(arguments);
var original = this;
return function() {
return original.apply(this, curriedArgs.concat(slice.call(arguments)));
};
};
})();
}
Run Code Online (Sandbox Code Playgroud)
if (!Function.prototype.curry) {
(function() {
var slice = Array.prototype.slice;
Function.prototype.curry = function() {
var curriedArgs = slice.call(arguments);
var original = this;
return function() {
return original.apply(this, curriedArgs.concat(slice.call(arguments)));
};
};
})();
}
function foo(a, b) {
snippet.log("a = " + a + ", b = " + b);
}
var curriedFoo1 = foo.curry(1);
curriedFoo1(2); // "a = 1, b = 2"Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)