Just a side remark in case someone lands here after reading only the title of the question.
I know the OP didn't want to use ES6 spread operators and explicitly asked for a call to bind()
, so my answer is apparently twice off-topic.
However, it appears the actual need was to apply bind()
to an unbound function (i.e. not a method), which makes bind
essentially unnecessary.
bind()
has to handle special cases (like enforcing the value of this
for a constructor) which costs some computation time that is wasted if you just want to apply some parameters to an ordinary function and don't care about this
to begin with.
A naive version of bind()
stripped of the sanity checks and OOP-specific fiddling with this
could be:
Function.prototype.naive_bind = function (fixed_this, ...fixed_args) {
const fun = this;
return function(...free_args) {
return fun.call(fixed_this, ...fixed_args, ...free_args);
}
}
So you can write your own pseudo-bind that drops this
and does a "partial application" of your actual parameters:
function partial_application (fun, ...applied_args) {
return function(...free_args) {
return fun.call(null, ...applied_args, ...free_args);
}
}
If you want to apply all your arguments and leave room for a last one, you can drop the extra parameters too:
function total_application (fun, ...applied_args) {
return function(free_arg) {
return fun.call(null, ...applied_args, free_arg);
}
}
If your arguments are inside an array, you can destructure them:
function total_application_from_array (fun, [...applied_args]) {
return function(free_arg) {
return fun.call(null, ...applied_args, free_arg);
}
}
I suppose you could use apply instead of call, but you'd have to add the extra free parameter to the array.
function total_application_from_array (fun, applied_args) {
return function(free_arg) {
return fun.apply(null, [...applied_args, free_arg]);
}
}
so you'd use that as:
var a = partial_application (console.log, 1, 2, 3);
a(4,5,6); // 1, 2, 3, 4, 5, 6
a("hello", "world"); // 1, 2, 3, hello, world
a = total_application (console.log, 1, 2, 3);
a() // 1, 2, 3, undefined
a(4, 5, 6) // 1, 2, 3, 4
a = total_application_from_array(console.log, [1,2,3]);
a(4,5,6) // 1, 2, 3, 4