Skipping An Argument Using The Javascript .bind() Method
Solution 1:
No such functionality exists in JavaScript, but it would be fairly straightforward to implement a function that does the same thing:
functioncurryWithNulls(fn, thisObj) {
var curriedArgs = Array.prototype.slice.call(arguments, 2);
var length = curriedArgs.length;
returnfunction() {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < length || args.length; i++) {
if (i >= length || curriedArgs[i] === null) {
curriedArgs[i] = args.shift();
}
}
return fn.apply(thisObj, curriedArgs);
}
}
functionfoo(arg1, arg2, arg3, arg4) {
console.log(arguments);
}
var curriedFoo = curryWithNulls(foo, this, 'bar', null, null, 'qux');
curriedFoo('baz', 'lel');
// => { '0': 'bar', '1': 'baz', '2': 'lel', '3': 'qux' }
This differs slightly from your example in that it requires a null
for each skipped argument (whereas in your example you have a single null
fill in for two arguments). This allows more complex constructions with curried arguments in any position, e.g.:
var curriedFoo2 = curryWithNulls(foo, this, null, 'bar', null, 'qux');
curriedFoo2('baz', 'lel');
// => { '0': 'baz', '1': 'bar', '2': 'lel', '3': 'qux' }
Solution 2:
No, you'd just be binding the null
.
The function's parameters are the function's parameters; binding a null
does exactly that, it doesn't redefine the function, it returns a new one with the same signature.
Solution 3:
It is possible with a functional composition:
var foo = function(arg1, arg2, arg3, arg4) { console.log(arguments); }
var bar = function(arg2, arg4) {
return foo.bind(this, 'bar', arg2, 'qux')();
}
bar('baz', 'lel');
or, with modern syntax:
constfoo = (arg1, arg2, arg3, arg4) => console.log(arguments);
constbar = (arg2, arg4) => foo.bind(this, 'bar', arg2, 'qux')();
bar('baz', 'lel');
or without bind at all:
constfoo = (arg1, arg2, arg3, arg4) => console.log(arguments);
constbar = (arg2, arg4) => foo(this, 'bar', arg2, 'qux', arg4);
bar('baz', 'lel');
P.S. Don't forget to call your binded function (note these () after bind);
Post a Comment for "Skipping An Argument Using The Javascript .bind() Method"