Skip to content

Instantly share code, notes, and snippets.

@ojhaujjwal
Created September 8, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ojhaujjwal/83946e3537b49d9aa0ee69f327c25372 to your computer and use it in GitHub Desktop.
Save ojhaujjwal/83946e3537b49d9aa0ee69f327c25372 to your computer and use it in GitHub Desktop.
Javascript Reduce Map
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);
});
});
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