Array.prototype.map()
Difficulty: Easy, Duration: 15 minutes, Languages: JS, TS, Author: Kiran Dash (opens in a new tab)
Watch the live Stream on YouTube (opens in a new tab)
Question
Array.prototype.map()
is a powerful utility function in JavaScript that allows you to transform each element of an array using a callback function. In this exercise, you will implement a simplified version of Array.prototype.map()
.
Example
example.ts
const double = (x: number) => x * 2;
const input = [1, 2, 3];
input.myMap(double); // [2, 4, 6]
Launch exercise in editor (opens in a new tab)
Solution
with .call()
method
solution.ts
Array.prototype.myMap = function (callbackFn, thisArg) {
if (typeof callbackFn !== "function" || !callbackFn.call) {
throw new TypeError(`${callbackFn} is not a function`);
}
// input array can be accessed using this keyword
const len = this.length;
const outputArr = Array(len);
for (let k = 0; k < len; k++) {
// Object.hasOwn is used to handle the edge case for sparse array and avoid getting NaN in result
if (Object.hasOwn(this, k)) {
outputArr[k] = callbackFn.call(thisArg, this[k], k, this);
}
}
return outputArr;
};
Edge Cases:
- Handling Sparse arrays ex:
[1, , 3]
wherethis.length
will be3
butthis[1]
will beundefined
. And we should not callcallbackFn
forundefined
values. We handled this by usingObject.hasOwn(this, k)
in the for loop. - Handling
index
andarray
as fn params: Calling thecallbackFn
using.call
method and passindex
andarray
as arguments. - Handling
thisArg
: IfthisArg
is passed, thecallbackFn
should not be an arrow function, as arrow functions do not have their ownthis
context. - Handling type check: If
callbackFn
is not a function or does not have acall
method, we throw aTypeError
.
Launch Solution in Editor (opens in a new tab)