Skip to content

Commit

Permalink
stress: utils like lodash / understore
Browse files Browse the repository at this point in the history
  • Loading branch information
jokester committed Apr 6, 2024
1 parent 97560f0 commit fe433a0
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/stress/groupBy.spec.ts
Original file line number Diff line number Diff line change
@@ -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],
});
});
});
16 changes: 16 additions & 0 deletions src/stress/groupBy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { DefaultMap } from '../collection/default-map';

export function groupBy<T, K extends string | number | symbol>(
values: Iterable<T>,
keyer: (value: T) => K,
): Record<K, T[]> {
return Object.fromEntries(groupByAsMap(values, keyer)) as Record<K, T[]>;
}

export function groupByAsMap<T, K>(values: Iterable<T>, keyer: (value: T) => K): ReadonlyMap<K, T[]> {
const map = new DefaultMap<K, T[]>(() => []);
for (const v of values) {
map.getOrCreate(keyer(v)).push(v);
}
return map;
}
12 changes: 12 additions & 0 deletions src/stress/orderBy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { orderBy } from './orderBy';

describe('orderBy', function () {

Check failure on line 3 in src/stress/orderBy.spec.ts

View workflow job for this annotation

GitHub Actions / check

Unexpected function expression
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]);
});
});
18 changes: 18 additions & 0 deletions src/stress/orderBy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* (for more complicated case, consider fp-ts Order<T> typeclass)
* @param values
* @param key
* @param asc
*/
export function orderBy<T, O>(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;
}

0 comments on commit fe433a0

Please sign in to comment.