HomePremium · ₹1199
← All questions

Implement Function.prototype.apply (myApply)

Medium
Asked at:AmazonPaytm
Was this asked in an interview?

Write myApply(fn, thisArg, argsArray) — like call, but arguments are passed as an array.

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 fn with this set to thisArg.
  • Spread argsArray into fn as individual arguments.
  • Default to no arguments when argsArray is omitted.
  • Return whatever fn returns.

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
}
Implement Function.prototype.apply (myApply) — JavaScript Interview Question | Mentoxis