Implement Function.prototype.apply under the name myApply. It does the same thing as Function.prototype.call — invoke the function with a given this value — except the arguments arrive as a single array (or array-like) rather than spread out one by one.
You'll attach the method to Function.prototype so that any function can call fn.myApply(thisArg, argsArray). The function must execute synchronously, with this rebound for the duration of that one call, and return whatever the original function returns.
// Defined on Function.prototype, so available on every function:
// fn.myApply(thisArg, argsArray)
//
// thisArg — the value to bind as `this` inside fn
// argsArray — an array or array-like; its elements become fn's positional args
// null/undefined means "call with zero args"
//
// returns — whatever fn returns
Function.prototype.myApply = function (thisArg, argsArray) { /* ... */ };
Bind this and pass arguments as an array:
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: 'Ada' };
greet.myApply(user, ['Hello', '!']); // 'Hello, Ada!'
Compare to myCall — same outcome, different argument shape:
greet.myCall(user, 'Hi', '?'); // 'Hi, Ada?'
greet.myApply(user, ['Hi', '?']); // 'Hi, Ada?' (array, not spread)
Borrowing array methods on an array-like (the classic arguments trick):
function sum() {
// `arguments` is array-like, not an array. Borrow Array.prototype.slice
// and apply it with `arguments` as the args list.
const args = Array.prototype.slice.myApply(arguments);
return args.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
argsArray may be null or undefined — treat it as "call with zero args", matching the spec.argsArray may be array-like — anything with a numeric length and indexed properties (arguments, a DOM NodeList, {0: 'a', length: 1}) should work. The spread operator handles this for you when the value is iterable; otherwise read indices up to length.apply, call, or bind — that defeats the exercise. The spread operator (fn(...args)) is allowed and is the natural tool here.arguments ceremony for variadic args — myApply itself takes exactly two named parameters; the array you receive is the argument list to forward.myApply is transparent: whatever fn returns, you return.