Implement bind polyfill
You are required to implement custom bind() polyfill from scratch that replicates its behavior including partial application.
bind()in JavaScript creates a new function with a fixedthisvalue and optionally preset arguments. It does not execute the function immediately; it returns a new function that will run later with the bound context. This is commonly used to ensure methods keep the correctthiswhen passed as callbacks.
The interviewer is testing whether you truly understand how bind works under the hood — not just how to use it. This is a classic deep-dive question that separates candidates who memorize from those who understand.
Example:
function multiply(a, b) {
return a * b;
}
const double = multiply.myBind(null, 2);
double(5); // 10
double(8); // 16
Tests (Jest):
describe('myBind', () => {
const multiply = (a, b) => a * b;
const add3 = (a, b, c) => a + b + c;
it('partial application (double 5)', () => {
expect(multiply.myBind(null, 2)(5)).toBe(10);
});
it('partial application (double 8)', () => {
expect(multiply.myBind(null, 2)(8)).toBe(16);
});
it('binds this context', () => {
const obj = { x: 42, getX: function() { return this.x; } };
expect(obj.getX.myBind(obj)()).toBe(42);
});
it('binds only this, args passed at call', () => {
expect(multiply.myBind(null)(2, 5)).toBe(10);
});
it('merges partial and call-time args', () => {
expect(add3.myBind(null, 1)(2, 3)).toBe(6);
});
});