Hi all,
I’m struggling with the exercise “Implement map on a Prototype” and would be most grateful for any help from the community, thanks in advance.
Link to the exercise:
This is my code:
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
for (let i = 0; i < this.length; i++) {
tempVariable = callback(this[i]);
newArray.push(tempVariable);
}
// Only change code above this line
return newArray;
};
From my understanding, “this” refers to the object that is calling the method, ie whichever array is calling the method, eg [23, 65, 98, 5, 13] or [“naomi”, “quincy”, “camperbot”] etc.
I’m saying iterate through the elements in the array. Then call whatever callback function is passed in, and I’ll pass into that callback function this[i]. I then push the value into the new array.
The weird thing is, if I try console logging the following in my own code editor:
console.log([23, 65, 98, 5, 13].myMap(item => item * 2));
console.log(["naomi", "quincy", "camperbot"].myMap(element => element.toUpperCase()));
console.log([1, 1, 2, 5, 2].myMap((element, index, array) => array[index + 1] || array[0]));
The first two produces what the challenge asks me. The last console.log throws an error.
But what’s weird is if I put the code I have into the fCC challenge, it says I got all of it wrong (except the requirement “Your code should not use the map
method.”)
I would be most grateful if someone could point me in the right direction. I think part of the problem is I also don’t really even understand what this part means:
[1, 1, 2, 5, 2].myMap((element, index, array) => array[index + 1] || array[0])
It seems the callback accepts multiple arguments “element, index, and array” and but I can’t get my head around the last part.
Any help would be greatly appreciated, thanks.