Created
September 8, 2020 09:37
-
-
Save ojhaujjwal/83946e3537b49d9aa0ee69f327c25372 to your computer and use it in GitHub Desktop.
Javascript Reduce Map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { reduceMap } from './reduce-map'; | |
describe('reduceMap', () => { | |
const sumValueAndSubtractKey = (result: number, value: number, key: number) => result + value - key; | |
it('should return initial value for empty map', () => { | |
expect( | |
reduceMap( | |
new Map(), | |
sumValueAndSubtractKey, | |
4, | |
), | |
).toEqual(4); | |
}); | |
it('should return accumulated value for non-empty map', () => { | |
expect( | |
reduceMap( | |
new Map([ | |
[5, 2], | |
[7, 4], | |
]), | |
sumValueAndSubtractKey, | |
2, | |
), | |
).toEqual(-4); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const reduceMap = <TMapKey, TMapValue, TResult> | |
( | |
map: Map<TMapKey, TMapValue>, | |
callback: (accumulator: TResult, value: TMapValue, key: TMapKey) => TResult, | |
accumulator: TResult, | |
) => { | |
let result = accumulator; | |
map.forEach((value, key) => result = callback(result, value, key)); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment