Cómo escribir su propio mapa, filtrar y reducir funciones en JavaScript

Un adelanto de la programación funcional y las funciones de orden superior en Javascript.

Siempre que escucho sobre programación funcional, lo primero que me viene a la mente son las funciones de orden superior. Para las personas que no conocen las funciones de orden superior, esto es lo que dice Wikipedia:

Una función de orden superior es una función que realiza al menos una de las siguientes acciones:

  • Toma una o más funciones como argumentos,
  • Devuelve una función como resultado.

Las funciones de orden superior se pueden describir mejor mediante las funciones de mapa, filtro y reducción. Javascript por defecto tiene su propia implementación de estas funciones. Hoy, escribiremos nuestro propio mapa, filtraremos y reduciremos funciones.

Nota: Tenga en cuenta que estas implementaciones de los métodos de mapa, filtro y reducción pueden no reflejar las implementaciones nativas de sus contrapartes de Javascript.

Mapa

De MDN:

El map()método crea una nueva matriz con los resultados de llamar a una función proporcionada en cada elemento de la matriz de llamada.

Parece bastante sencillo. ¡Ahora veamos el Javascript map()en acción!

let arr = [1, 2, 3, 4, 5];
// pass a function to mapconst squareArr = arr.map(num => num ** 2);
console.log(squareArr); // prints [1, 4, 9, 16, 25]

Entonces, ¿qué acaba de pasar? Escribimos una función que devuelve el cuadrado de un número y pasamos esa función como argumento a nuestro map(). Veamos las instrucciones paso a paso sobre cómo crear nuestra propia función de mapa.

  1. Crea una matriz vacía mapArr.
  2. Recorre los elementos de la matriz.
  3. Llamar a la función mapFunccon el elemento actual como argumento.
  4. Empuje el resultado de la mapFuncfunción a la mapArrmatriz.
  5. Devuelve la mapArrmatriz después de pasar por todos los elementos.

Ahora escribamos nuestra implementación del map()

// map takes an array and function as argumentfunction map(arr, mapFunc) { const mapArr = []; // empty array // loop though array for(let i=0;i

Now if you call the new map() in the previous example code,

const squareArr2 = map(arr, num => num ** 2);
console.log(squareArr2); // prints [1, 4, 9, 16, 25]

Pretty cool huh? Let’s jump into filter() next.

Filter

From MDN:

Original text


The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let’s see an example:

let arr = [1, 2, 3, 4, 5];
// pass a function to filterconst oddArr = arr.filter(num => num % 2 === 0);
console.log(oddArr); // prints [2, 4]

The filter function took a function which will return true if a number is even. The filter() “filters” the input array based on whether the element is true or false. Let’s go through step by step on how the filter() works.

  1. Create an empty array filterArr.
  2. Loop through the array elements.
  3. Called the filterFunc function with the current element as the argument.
  4. If the result is true, push the element to the filterArr array.
  5. Return filterArr array after going through all the elements.

Time to write our own filter()

// filter takes an array and function as argumentfunction filter(arr, filterFunc) { const filterArr = []; // empty array // loop though array for(let i=0;i

Let’s see if our new filter() works out with the previous example:

const oddArr2 = filter(arr, num => num % 2 === 0);
console.log(oddArr2); //prints [2, 4]

Neat! I have saved the best and hardest one for the last. Let’s go to reduce() next.

Reduce

From MDN:

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

Makes sense? No? Here’s an example to wrap your head around:

let arr = [1, 2, 3, 4];const sumReducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4const sum = arr.reduce(sumReducer);console.log(sum);// prints 10
// 5 + 1 + 2 + 3 + 4const sum2 = arr.reduce(sumReducer);console.log(sum2);// prints 15

Starting to get a picture? Let’s make it clear. Before digging too deep into the reduce() method, you might need to get acquainted with the reducer function.

If you have used reduxin the past, you might have some idea about what a reducer function is. In the example above, the reducer function is written as the sum between the accumulator and current value. When you pass the reducer function to the reduce() method, it will loop through each number in the array and adds it to the accumulator ( 0 at the beginning), which itself becomes the new accumulator for the next iteration. This continues till the end of the array and returns the accumulator as a result.

If I had to output the value of the accumulator in each step for the above example, it would be like this:

  • Before the start of the iteration, accumulator = 0
  • 1st iteration, accumulator += 1; // accumulator = 1
  • 2nd iteration, accumulator += 2; // accumulator = 3
  • 3rd iteration, accumulator += 3; // accumulator = 6
  • 4th iteration, accumulator += 4; // accumulator = 10

Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array. It ultimately becomes the final, single resulting value.

If you are still stuck at some point, try writing some operations with the inbuilt reduce() method. Whenever you feel you are ready, go through the next steps on how to implement your custom reduce():

  1. Initialize accumulator variable with 0 or initalValue argument from the reduce().
  2. Loop through the array elements.
  3. Call the reducer function with the accumulator and current element as the arguments.
  4. Return accumulator after going through all the elements.

Alright, time to code.

// reducer takes an array, reducer() and initialValue as argumentfunction reduce(arr, reducer, initialValue) { let accumulator = initialValue === undefined ? 0 : initialValue // loop though array for(let i=0;i

Well, that was easier than expected. Let’s see if it’s working.

const sum = reduce(arr, sumReducer);
console.log(sum); // prints 10
const sum2 = reduce(arr, sumReducer, 5);
console.log(sum2);// prints 15

Works like a charm!

That’s it :)

Comment down below if you have any questions.