Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do higher-order functions like `map()` and `reduce()` receive their data?

Tags:

javascript

I'm trying to write my own higher order function right now and I want to know how functions like map() and reduce() access the array they are being applied to. And not just for arrays either, but with any higher order function like toString() or toLowerCase().

array.map()
^^^ // How do I get this data when I am writing my own higher order function?

array.myOwnFunction(/* data??? */)

I hope this makes sense. I'm sure the answer is out there already, but I'm struggling to know what to search for to find the information.

like image 902
Joss Classey Avatar asked Aug 22 '19 15:08

Joss Classey


2 Answers

You can add it to the Array prototype like :

Array.prototype.myOwnFunction = function() {
  for (var i = 0; i < this.length; i++) {
    this[i] += 1;
  }

  return this;
};

const array = [1, 2, 3];

const result = array.myOwnFunction();

console.log(result);
like image 150
Taki Avatar answered Oct 31 '22 16:10

Taki


Check the polyfill for Array.prototype.map(), this line in particular:

//  1. Let O be the result of calling ToObject passing the |this| 
//    value as the argument.
var O = Object(this);

Simplifying, this is where the values are received.

like image 32
silentw Avatar answered Oct 31 '22 16:10

silentw