Overview
Implement fnBind(fn, thisArg, ...boundArgs) that returns a new function with this bound to thisArg and initial arguments pre-filled.
Constraints
- Do not use
Function.prototype.bind.
Examples
function add(a, b) { return this.x + a + b; }
const bound = fnBind(add, { x: 10 }, 1);
bound(2); // 13Solution
Reveal solution
function fnBind(fn, thisArg, ...boundArgs) {
return function(...args) {
const ctx = Object(thisArg);
const key = Symbol();
ctx[key] = fn;
const result = ctx[key](...boundArgs, ...args);
delete ctx[key];
return result;
};
}function-prototype-bind.js
Function.prototype.bind
easycodingJavaScriptFunctions
Overview
Implement fnBind(fn, thisArg, ...boundArgs) that returns a new function with this bound to thisArg and initial arguments pre-filled.
Constraints
- Do not use
Function.prototype.bind.
Examples
function add(a, b) { return this.x + a + b; }
const bound = fnBind(add, { x: 10 }, 1);
bound(2); // 13Solution
Reveal solution
function fnBind(fn, thisArg, ...boundArgs) {
return function(...args) {
const ctx = Object(thisArg);
const key = Symbol();
ctx[key] = fn;
const result = ctx[key](...boundArgs, ...args);
delete ctx[key];
return result;
};
}NameTopicDifficulty
103 of 103 problems