Functional Programming: Implement Map on a Prototype

Struggling through researching callback functions.The below solution isn’t working for me. Can someone tell me what is wrong with my code here? Thanks in advance!

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
var newArray = [];
var copyS= s.slice();
// Add your code below this line
for(let i=0;i<copyS.length; i++){
newArray[i]=(callback(copyS[i]));
console.log(newArray);
}
// Add your code above this line
return newArray;

};

var new_s = s.myMap(function(item){
return item * 2;
});

2 Likes

Your solution works when I test it.

Yup, copied it, pasted it into https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype/, and it passes. What seems to be the problem you’re having?

One thing I might suggest, though – remember you won’t always have access to the global variable s. By coding your function to look for that, you have created a ‘brittle’ function. Instead, bear in mind that you’re writing to the prototype of the Array object, which means that when you run your function. you’d run it by s.myMap(...) – which means that, within your function, you have a this pseudo-variable.

Instead of forcing other coders who use your function to have a global s variable, you can simply change your line var copyS = s.slice(); to var arrayCopy = this.slice();. You can do this, because within your function, the context is the Array instance from which you’re calling the function. So it doesn’t need to know about s or any other global, it simply knows its running on an Array, and that this is the specific array it is referring to with this. If that makes any sense at all.

1 Like

That is super helpful feedback thank you!

My error in the fcc console was “copyS is not a function”. But I erased my code and input the code above and it worked. Maybe I accidentally deleted a piece. Thanks!

1 Like

Glad I could help, but it sounds like you did all the heavy lifting…