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;
}
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;
}
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'
]
*/
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.
Top comments (0)