Implement map on a Prototype (concept clarification)

Tell us what’s happening:
I just want to double check that I have the concepts right for this lesson, as described in my comments below. Could someone correct me if I’m wrong on some of this? My code works and I THINK i understand it all, but this seems foundational, and I don’t want to get it wrong. TIA

P.S. I originally came here for help solving this, but during the commenting process, laying it out line by line, things became a lot more clear.

Your code so far


// This is a global array which we don't want to change directly because it's bad practice to do so
// and does not follow the model of functional programming
var originalMonaLisa = [23, 65, 98, 5]; 

// We are giving ALL arrays within our code the ability to use a thing 
// we're calling myMap, which accepts an argument called callback
Array.prototype.myMap = function(callback){

/* We are building a newArray based off the global one so that we don't 
 do anything to change the original array or break something.
 It's like doing our work on a photocopy of the original instead of the original Mona Lisa  
*/
  var photocopyOfMonaLisa = [];

/* For each thing inside the array we use myMap with (aka originalMonaLisa.myMap)
We don't just want to copy that thing to our new photocopy of the Mona Lisa,
but also give our Photocopy the ability to do something to each pixel of it as well.
That's why we push in the callback function instead of just pushing pixel by itself.
*/
    this.forEach(pixel => photocopyOfMonaLisa.push(callback(pixel)));
  return photocopyOfMonaLisa;
};


// Make a new version of the Mona Lisa that's twice the size
// (aka double each "pixel" in the Mona Lisa)
var new_s = originalMonaLisa.myMap(function(item){
  return item * 2;
});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.127.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype/

1 Like

That’s a pretty clear commentary, and very well explained. The only issue I might suggest is with the variable name photocopyOfMonaLisa – don’t think that this is limited to your originalMonaLisa array. I might suggest using a more generic name, like returnArray for that. Then you just return returnArray;

Dang it. I want the functionality to like your post TWICE!

1 Like

Awesome, thank you for that response! I’m constantly wavering between “just make this example work” and “make this example ALWAYS work”. Making that distinction with the variable name helps me wrap my brain around doing that!

I’m super happy that my understanding of the material wasn’t out of whack, because it took a LOT of re-reading to get there. :laughing:

1 Like