Let's implement some High-Order functions map, filter, any ...

Published on:

Poundring over the daily life, our bodies or in the nature, We always observe that it is all about input => process => output. In the software industry processes represented in shape of functions(methods) are considered build blocks for modelling any system workflow.

So a function is an operation consisting of one or many instructions where an input is processed and output is resulted. Simple as that. Functions in JavaScript have some extra powers.function can be passed as argument, and a function can return another function. This is what we call high-order functions.

Function returns another function

  function multiplyByBase(x) {
    return function(y) {
      return x*y;
    }
  }

  const multiplyBy5 = multiplyByBase(5) // specify base to be 5
  console.log(multiplyBy5(10)) // output: 50;
  console.log(multiplyBy5(5)) // output: 25;

This exact usage is one of the most powerful aspects of JavaScript functions. It introduces us to Closures. I will talk about this concept later on in other blogs.

Function as argument

  const arr = [1,2,3];

  function evenOrOdd(items, testIfEven) {
    const result = [];
    
    for(const n in items) {
      if(testIfEven(n)) result.push('Even');
      else result.push('Odd');
    }

    return result;
  }

  function checkEven(number) {
    return number % 2 === 0;
  }

  const res = evenOrOdd(arr, checkEven);
  console.log(res) // ['Odd','Even','Odd']

In this example you can see clearly how we test our numbers on a specific condition. We could have done it inside the evenOrOdd function but taking that outside is better for readability. Of course in bigger project you might have complicated business logics and passing functions helps a lot.

Now Let’s see how can we implement some famous Array functions such as: forEach, map, filter, any, and others.

ForEach

  const forEach = (arr, consumer) => {
    for(let i = 0; i < arr.length; i++) {
      consumer(arr[i]);
    }
  }

  const items = [1,2,3,4];

  forEach(items, console.log);

The ouput for this code snippet is just elements of the items printed different lines. Now observe how we passed console.log as argument to the forEach

Filter

filter method in Array class is applied on the Array and takes a predicate as argument. and it returns a new object Array that passes the predicate function.

  const filter = (arr, predicate) => {
    const passed = [];
    for(let i = 0; i < arr.length; i++) {
      if(predicate(arr[i])) passed.push(arr[i]);
    }

    return passed;
  }

  const isEven = (item) => {
    return item % 2 === 0;
  }

  const items = [1,2,3,4];

  const evenNumbers = filter(items, isEven);
  //[2,4]

Map

map method in Array class is applied on the Array and takes a mapper function as argument. and it returns a new object Array that maps elements.

  const map = (arr, mapper) => {
    const mapped = [];
    for(let i = 0; i < arr.length; i++) {
      mapped.push(mapper(arr[i]))
    }

    return mapped;
  }

  const square = (item) => {
    return item * item;
  }

  const items = [1,2,3,4];

  const squared = map(items, square);
  //[1,4,9,16]

Reduce

reduce method in Array class is applied on the Array. It takes a combine function and an initial value that specifies which data type to return. Example if we are summing numbers initial value is to be 0 if we want to return an object inital value is an empty object {}, if the returned value is an Array then we specify initial value as an empty array [];

In this example we are going to sum the numbers in our array.

  const reduce = (arr, combine,initialValue) => {
    let sum = initialValue;
    for(let i = 0; i < arr.length; i++) {
      sum = combine(sum, arr[i]);
    }

    return sum;
  }

  const sumTwoNumbers = (a,b) => {
    return a + b;
  }

  const items = [1,2,3,4];

  const sum = reduce(items, sumTwoNumbers, 0);
  console.log(sum); // 10

Conclusion

In this article we tackled some basic implementation of Array methods. As you saw, it is not difficult to re-implement them. The purpose of this article is first demonstrate Array methods and also make the reader curious about the deeper implementation of these functions.

references:

[1] eloquentjavascript

[2] MDN-Array