How To Implement JavaScript Utility Functions Using Reduce?



    When it comes to code in JavaScript, developers found reduce function as one of the toughest concepts to crack. According to Wikipedia, Reduce has multiple names viz. Accumulate, Fold, Compress and Aggregate. These names clearly indicate the meaning & working of reduce function. The idea behind this is to break down a structure into a single value. Hence, Reduce can be defined as a function which converts a list into any data type.

    For example, you can reduce an array [5,4,3,2,1] into the value 15 by just adding them.

    Reduce function keeps developers away from using loop in order to fold a list into a single value.

    In this blog, you will learn ways to implement well-known functions using reduce as already done by developers in top software development company.

    I have listed out 10 JavaScript utility functions recreated using reduce function. So, check out below these functions:-

    • Map


    Parameters used


    array (to transform list of items), transform Function (is a function used to run on each element)

    Working


    By using the given transformFunction, each element in the given array get transformed and returns new array of items.

    How to implement?


    const map = (transformFunction, array1) =>
      array1.reduce((newArray1, xyz) => 
    {
    	newArray1.push(transformFunction(xyz));
    
    	return newArray1;
      }, 
    []
    );
    

    Use case:


    const double = (x) => x * 2;
    const reverseString = (string) =>
      string
    	.split('')
    	.reverse()
    	.join('');
    
    map(double, [200, 300, 400]);
    
    Output: [400, 600, 800]
    
    map(reverseString, ['Hello Alka', 'I love cooking']);
    // ['alkA olleH', ‘gnikooc evol I']
    

    • Reject


    Parameters used


    array (list of items/values to filter), predicate (function returning true or false value)

    Working

    Reject has an opposite behaviour to filter but same like that. If predicate returns false value then only item will get added to the new array. Else, the item will be excluded from the new array.

    How to implement?


    const reject = (predicate, arr3) =>
      arr3.reduce((newArray, val3) => {
    	if (predicate(val3) === false) {
      	newArray.push(val3);
    	}
    
    	return newArray;
      }, 
    []
    );

    Use case:


    const isEven = (z) => z % 2 === 0;
    
    reject(isEven, [1, 6, 4, 3]);
    // [1, 3]
    
    reject(equals4, [4, 2, 4, 3]);
    // [2, 3]
    

    • Scan


    Parameters used


    array (list of items), reducer (is a function which receives two parameters i.e. accumulator & current element from the list of array )

    Working


    Its working is similar to reduce but instead of returning the single value as a result, it returns a list of every reduced value corresponding to the single output.

    How to implement?


    const scan = (reducer, initialVal, array) => {
      const reducedValues = [];
    
      array.reduce((acc, currentval) => {
    	const newAcc = reducer(acc, currentval);
    
    	reducedValues.push(newAcc);
    
    	return newAcc;
      }, initialVal);
    
      return reducedValues;
    };

    Use case:


    const add = (y, z) => y + z;
    const multiply = (y, z) => y * z;
    
    scan(add, 0, [1, 2, 3, 4]);
    // [1, 3, 6, 10] 
    
    scan(multiply, 1, [1, 2, 3, 4]);
    // [1, 2, 6, 24] 

    • Filter


    Parameters used


    array (to filter list of items), predicate (is a function to return false or true value)

    Working


    Here, you will get a new array as the output. If the predicate function returns true value then the item will be added to the new array. However, if it returns false then the item will be excluded from the new array.

    How to implement?


    const filter = (predicate, arr1) =>
      arr1.reduce((newArray, val) => 
    {
    	if (predicate(val) === true) {
      	newArray.push(val);
    	}
    
    	return newArray;
      }, 
    [
    ]
    );

    Use case:


    const isEven = (y) => y % 2 === 0;
    
    filter(isEven, [3, 2, 5]);
    // [2]
    
    filter(equals3, [7, 1, 3, 6, 3]);
    // [3, 3]
    

    • None


    Parameters used


    array (list items to test), predicate (function to return value true or false)

    Working


    Here, none returns true value if predicate returns false value for every item. Else it will return false value for every true value of predicate.

    How to implement?


    const none = (predicate, array) =>
      array.reduce((acc1, val1) => !acc1 && !predicate(val1), false);
    

    Use case:


    const isEven2 = (x) => x % 2 === 0;
    
    none(isEven2, [1, 3, 5]); // true
    none(isEven2, [1, 3, 4]); // false
    none(sequl3, [1, 2, 4]); // true
    none(sequl3, [1, 2, 3]); // false

    • Partition


    Parameters used


    array (contains a list of items), predicate (function returning false or true value)

    Working


    It defines the splitting of an array into two based upon the predicate value. If predicate returns a true value then the item will go to list1. Else, it will go to the list2. The method to split the array into various chunks has been used by the modern-day programmers that are associated with the top software development companies. Let’s take a look into the further steps:

    How to implement?


    const partition = (predicate, array) =>
      array.reduce(
    	(result3, item) => {
      	const [list1, list2] = result;
    
      	if (predicate(item) === true) {
        	list1.push(item);
      	} else {
        	list2.push(item);
      	}
    
      	return result3;
    	},
    	[
    [], []
    ]
      );

    Use case:


    const isEven = (z) => z % 2 === 0;
    
    partition(isEven, [1, 2, 3]);
    // [[2], [1, 3]]
    
    partition(isEven, [1, 3, 5]);
    // [[], [1, 3, 5]]
    
    partition(equals3, [1, 2, 3, 4, 3]);
    // [[3, 3], [1, 2, 4]]
    
    partition(equals3, [1, 2, 4]);
    // [[], [1, 2, 4]]
    

    • All


    Parameters used


    array (to test the list of the items), predicate (is a function to return value true or false)

    Working


    On providing an input value, if predicate returns value true then all will return value true. Else, it will return a false value.

    How to implement?


    const all = (predicate, array) =>
      array.reduce((arr, val) => arr && predicate(val), true);

    Use case:


    const sequl3 = (x) => x === 3;
    
    all(sequl3, [3]); // true
    all(sequl3, [3, 3, 3]); // true
    all(sequl3, [1, 2, 3]); // false
    all(sequl3, [3, 2, 3]; // false

    • Some


    Parameters used


    array (to test the list of items), predicate (is a function to return value true or false)

    Working


    For any input value, if predicate returns true, then some will return true. Otherwise, it will return a false value.

    How to implement?


    Let’s take an example for it:

    const some = (predicate, array) =>
      array.reduce((arc, val) => arc || predicate(val), false); 

    Use case:


    const aqua3 = (x) => x === 3;
    
    some(aqua3, [3]); // it is true
    some(aqua3, [3, 3, 3]); // it is true
    some(aqua3, [1, 2, 3]); // it is true
    some(aqua3, [2]); // it is false

    • Pluck


    Parameters used


    array (to store value of the items), key (to pluck key name from the object)

    Working


    It can pluck the given key off from each item in the array and further returns a new array of the respective values.

    How to implement?


    const pluck = (key3, array) =>
      array.reduce((values3, current) => {
    	values.push(current[key3]);
    
    	return values3;
      }, 
    
    []
    );

    Use case:


    pluck('name', [{ name: 'Soman' }, { name: 'Rovin' }, { name: 'Jojo' }]);
    // ['Soman', 'Rovin', 'Jojo']
    
    pluck(0, [[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
    // [1, 4, 7]

    • Find


    Parameters used


    array (to search items in the list of array), predicate (function returning false or true value)

    Working


    It will return the first element which matches the given predicate and in case if no match is found, then undefined is returned back.

    How to implement?


    const find = (predicate, array) =>
      array.reduce((output, item) => {
    	if (output !== undefined) {
      	return output;
    	}
    
    	if (predicate(item) === true) {
      	return item;
    	}
    
    	return undefined;
      }, undefined);

    Use case:


    const isEven = (a) => a % 2 === 0;
    
    find(isEven, []); // undefined
    find(isEven, [1, 2, 5]); // 2
    find(isEven, [5, 3, 7]); // undefined
    find(equals3, [5, 2, 3, 4, 3]); // 3
    find(equals3, [7, 2, 4]); // undefined
    

    Final Note:


    This is how can you implement JavaScript utility functions using reduce in less time. This will definitely aid software developers in saving time as well as their coding efforts. In case you need perfect support for your coding queries, you can contact to expert software development company for your project needs.
    Share post
    AdBlock has stolen the banner, but banners are not teeth — they will be back

    More
    Ads

    Comments 0

    Only users with full accounts can post comments. Log in, please.