DEV Community

Michal M.
Michal M.

Posted on • Edited on • Originally published at geodev.me

1 1

Own reduce method using Typescript

In my previous post I presented my approach to implement my own versions of some higher order functions in JavaScript. I covered three of them and one, a very powerful one was missing.
The Array.prototype.reduce.

In this short post, I'd like to show you my take on this higher order function using Typescript.

First, let's extend the Array prototype types. That's the part I'm not sure of. The Typescript compiler does not complain, but I feel that's something's wrong here. If you know what, let me know.

interface Array<T> {
    myReduce(cb: (previousValue: T, currentValue: T, index: number, array: T[]) => T, initialValue: T): T;
}
Enter fullscreen mode Exit fullscreen mode

And the function itself should look like this:

Array.prototype.myReduce = function<ReducedElem, ReducedValue>(callback: (previousValue: ReducedValue, currentValue: ReducedElem, index: number, array: ReducedElem[]) => ReducedValue, initialValue: ReducedValue): ReducedValue {
    let i = 0;
    let reduced = initialValue;

    if (arguments.length < 2) {
        i = 1;
        reduced = this[0];
    }
    for (i = 0; i < this.length; i++) {
        reduced = callback(reduced, this[i], i, this)
    }

    return reduced;
}
Enter fullscreen mode Exit fullscreen mode

I've tested this solution with a few examples.

// Classic usage - sum the numbers in the array
const numbers = [1, 10, 100, 1000];
numbers.myReduce((sum, curr) => sum + curr, 0) // Result: 1111

// Find the most recent date
const dates = [
  '1999/01/01',
  '2022/12/01',
  '2010/05/01',
  '2022/01/01'
];
dates.myReduce((max, curr) => curr > max ? curr : max, dates[0]) // Result: '2022/12/01'

// Flatten an array
const persons = [['Andrew', 'Joe'], ['Margaret', 'Sylvia'], ['Andrew', 'Rebecca', 'Joe', 'Sylvia']];
persons.myReduce((flatArray, currArray) => flatArray.concat(currArray), [])
/* [
      'Andrew', 'Joe', 'Margaret', 'Sylvia', 'Andrew', 'Rebecca', 'Joe', 'Sylvia'
   ]
*/
Enter fullscreen mode Exit fullscreen mode

These examples work fine and gave me the expected results. The Typescript compiler is not complaining about these examples as well.
For more information about typing function I recommend to get familiar with a Functions chapter on the Typescript official site.

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay