From fe433a041d1f72747e00c1c0ae9e461543de9af7 Mon Sep 17 00:00:00 2001 From: Wang Guan Date: Sun, 7 Apr 2024 00:05:29 +0900 Subject: [PATCH] stress: utils like lodash / understore --- src/stress/groupBy.spec.ts | 11 +++++++++++ src/stress/groupBy.ts | 16 ++++++++++++++++ src/stress/orderBy.spec.ts | 12 ++++++++++++ src/stress/orderBy.ts | 18 ++++++++++++++++++ 4 files changed, 57 insertions(+) create mode 100644 src/stress/groupBy.spec.ts create mode 100644 src/stress/groupBy.ts create mode 100644 src/stress/orderBy.spec.ts create mode 100644 src/stress/orderBy.ts diff --git a/src/stress/groupBy.spec.ts b/src/stress/groupBy.spec.ts new file mode 100644 index 0000000..9648922 --- /dev/null +++ b/src/stress/groupBy.spec.ts @@ -0,0 +1,11 @@ +import { groupBy } from './groupBy'; + +describe(groupBy, () => { + it('groups value with provided keyer()', () => { + expect(groupBy([], () => 0)).toEqual({}); + expect(groupBy(new Set([1, 2, 4]), (v) => v % 2)).toEqual({ + 1: [1], + 0: [2, 4], + }); + }); +}); diff --git a/src/stress/groupBy.ts b/src/stress/groupBy.ts new file mode 100644 index 0000000..bed1f0d --- /dev/null +++ b/src/stress/groupBy.ts @@ -0,0 +1,16 @@ +import { DefaultMap } from '../collection/default-map'; + +export function groupBy( + values: Iterable, + keyer: (value: T) => K, +): Record { + return Object.fromEntries(groupByAsMap(values, keyer)) as Record; +} + +export function groupByAsMap(values: Iterable, keyer: (value: T) => K): ReadonlyMap { + const map = new DefaultMap(() => []); + for (const v of values) { + map.getOrCreate(keyer(v)).push(v); + } + return map; +} diff --git a/src/stress/orderBy.spec.ts b/src/stress/orderBy.spec.ts new file mode 100644 index 0000000..8c9cb02 --- /dev/null +++ b/src/stress/orderBy.spec.ts @@ -0,0 +1,12 @@ +import { orderBy } from './orderBy'; + +describe('orderBy', function () { + it('sorts value DESC by "natural" JS ordering', () => { + expect(orderBy([2, 3, 1], (v) => v)).toEqual([3, 2, 1]); + expect(orderBy([1, 1, 2], (v) => v)).toEqual([2, 1, 1]); + }); + it('sorts value ASC by "natural" JS ordering', () => { + expect(orderBy([2, 3, 1], (v) => v, true)).toEqual([1, 2, 3]); + expect(orderBy([1, 1, 2], (v) => v, true)).toEqual([1, 1, 2]); + }); +}); diff --git a/src/stress/orderBy.ts b/src/stress/orderBy.ts new file mode 100644 index 0000000..fdbe34f --- /dev/null +++ b/src/stress/orderBy.ts @@ -0,0 +1,18 @@ +/** + * (for more complicated case, consider fp-ts Order typeclass) + * @param values + * @param key + * @param asc + */ +export function orderBy(values: T[], key: (v: T) => O, asc = false): T[] { + const indexes = values.map((v, i) => ({ v, i })); + return indexes.sort((a, b) => (asc ? compare(a.v, b.v) : -compare(a.v, b.v))).map((_) => _.v); +} + +function compare(a: any, b: any): number { + if (a < b) { + return -1; + } else if (a > b) { + return 1; + } else return 0; +}