DEV Community

Randy Rivera
Randy Rivera

Posted on

Functional Programming: Implementing map on a Prototype

  • Alright so continuing where we left off last time, map is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.

  • You might learn a lot about themap method if you implement your own version of it. It is recommended you use a for loop or Array.prototype.forEach().

  • Ex:

var s = [24, 55, 96, 4];

Array.prototype.myMap = function(callback) {
  var newArray = [];
  // Only change code below this line

  // Only change code above this line
  return newArray;
};

var new_s = s.myMap(function(item) {
  return item * 2;
});
Enter fullscreen mode Exit fullscreen mode
  • The Array instance can be accessed in the myMap method using this.
var s = [24, 55, 96, 4];

Array.prototype.myMap = function(callback) {
  var newArray = [];

for (let i = 0; i < this.length; i++) { // <---
  newArray.push(callback(this[i]))
}
  return newArray;
};

var new_s = s.myMap(function(item) {
  return item * 2;
});
Enter fullscreen mode Exit fullscreen mode
  • new_s should equal [48, 110, 192, 8].

Larson, Quincy, editor. “Implementing map on a Prototype.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.

Top comments (0)