Problem
Implement myApply(fn, thisArg, argsArray) — a standalone version of Function.prototype.apply.
apply is identical to call except the arguments arrive as a single array. This is handy when the number of arguments is dynamic (e.g. Math.max.apply(null, numbers) before the spread operator existed).
Your myApply(fn, thisArg, argsArray) must:
- Invoke
fnwiththisset tothisArg. - Spread
argsArrayintofnas individual arguments. - Default to no arguments when
argsArrayis omitted. - Return whatever
fnreturns.
Input
function sum(a, b) {
return a + b + this.n;
}
myApply(sum, { n: 1 }, [2, 3]);
Expected output
6
Implement from scratch:
function myApply(fn, thisArg, argsArray = []) {
// Your code here
}