Sitemap
Charles Bayley

Charles Bayley

Re-implementation of Array Higher Order Functions in JavaScript

Examples of Map Without Higher Order Functions

2 min readMar 19, 2018

--

Say we have an array like:

const numbers = [1, 2, 3, 4, 5];

Now say we want to square all elements of this array. We may do that as:

const squaredNumbers = [];for (let i = 0; i < numbers.length; i++) {
squaredNumbers.push(numbers[i] * numbers[i]);
}

Lets do the same thing but this time, lets double the elements:

const doubledNumbers = [];for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(arr[i] * 2);
}

Now, I happen to see a place for abstraction here. Let me explain: Both of these examples are taking an existing array and pushing each and every element into a new array after running some modification code on that element.

Get Charles Bayley’s stories in your inbox

Join Medium for free to get updates from this writer.

Lets pull the examples apart a bit more so you can see what I mean:

const squaredNumbers = [];const square = (number) => {
return number * number;
}
for (let i = 0; i < numbers.length; i++) {
const element = numbers[i];
squaredNumbers.push(square(element));
}

Now lets refactor the doubling example:

const doubledNumbers = [];const double = (number) => {
return number * 2;
}
for (let i = 0; i < numbers.length; i++) {
const element = numbers[i];
doubledArr.push(double(element));
}

With both examples I pulled out the code that modifies the elements into its own function and I set the current element as a variable to make it clear we are only operating with the elements one at a time.

Re-implementation of map

Now I want to make code that does the same thing as above with a single function call, as follows:

const map = (operation, array) => { 
/* TODO: implementation below */
}
const squaredNumbers = map(numbers, square);
const doubledNumbers = map(numbers, double);

Now lets implement a map function:

const map = (array, operation, thisArg = undefined) => {
const newArray = [];
for (let index = 0; index < array.length; index++) {
const element = array[index];
const newElement = operation.call(thisArg, element,
index, array);
newArray.push(newElement);
}
return newArray;
}

This code should now be completely equivalent to the following:

const map = (array, operation, thisArg = undefined) => {
return array.map(operation, thisArg);
}

I hope you enjoyed!

Working example

--

--