ООП в JavaScriptРасширяем прототипmedium

Полифил Array#map

Реализуйте полифил стандартного метода Array#map.

Это задача на работу с this. Упрощенную версию можно реализовать в задаче map.

Аргументы

  • callback — A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:
    • element — The current element being processed in the array.
    • index — The index of the current element being processed in the array.
    • array — The array map() was called upon.
  • thisArg [Optional] — A value to use as this when executing callbackFn

Подробнее про второй аргумент thisArg можно прочитать на MDN. Важная в контексте данной задачи информация:

  • The thisArg argument (defaults to undefined) will be used as the this value when calling callbackFn. The this value ultimately observable by callbackFn is determined according to the usual rules: if callbackFn is non-strict, primitive this values are wrapped into objects, and undefined/null is substituted with globalThis. The thisArg argument is irrelevant for any callbackFn defined with an arrow function, as arrow functions don't have their own this binding.

Возвращаемое значение

A new array with each element being the result of the callback function.

Примеры

Базовые примеры:

console.log([1, 2, 3].map2(x => x ** 2)); // [1, 4, 9] console.log(["a", "b", "c", "d"].map2((x, i) => x.repeat(i))); // ["", "b", "cc", "ddd"]

Пример использования второго аргумента:

const multiplicator = { x: 5, multiply(num) { return num * this.x; }, }; console.log([1, 2, 3].map2(multiplicator.multiply)); // [NaN, NaN, NaN] console.log([1, 2, 3].map2(multiplicator.multiply, multiplicator)); // [5, 10, 15]