• 0

Use map to accept an additional argument in javascript

Problem

Write a function Array.prototype.map() which can accept one additional argument.

function mul(x) {
  return x * x;
}

console.log([1, 2, 3].map(mul)); // [1, 4, 9]

Modify the function so that it can accept an additional argument

var mulWAdjustment = function(x, variance) {
    return (x * x + variance);
}

This post is a follow-up of
- Closures JavaScript interview question
I recommend reading it first, as it covers the basics of closures.

Logic 1

  • Using bind.
  • The first argument to the bind sets the context, which we do not need to set in this case.
  • The second argument to the bind is passed as the first argument to the callback, which we can use as an additional argument.

Logic 2

  • Using callbacks.
  • First argument to the map returns a callback function which accepts one argument. But it also has the access to the variance in the closures.

Solution


Reference