Skip to content

Commit

Permalink
feat: _mapBy
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillgroshkov committed Oct 30, 2023
1 parent eca06b8 commit bed09c6
Show file tree
Hide file tree
Showing 3 changed files with 275 additions and 236 deletions.
32 changes: 26 additions & 6 deletions src/array/array.util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
_intersection,
_last,
_lastOrUndefined,
_mapBy,
_mapToObject,
_max,
_maxBy,
Expand Down Expand Up @@ -97,19 +98,38 @@ test('_by', () => {
ab: { a: 'ab' },
})

r = _by(a, v => v.a)
expect(r).toEqual({
aa: { a: 'aa' },
ab: { a: 'ab' },
})

r = _by(a, v => v.a?.toUpperCase())
expect(r).toEqual({
AA: { a: 'aa' },
AB: { a: 'ab' },
})
})

test('_mapBy', () => {
const a = [{ a: 'aa' }, { a: 'ab' }, { b: 'bb' }]
expect(_mapBy(a, r => r.a)).toMatchInlineSnapshot(`
Map {
"aa" => {
"a": "aa",
},
"ab" => {
"a": "ab",
},
}
`)

expect(_mapBy(a, r => r.a?.toUpperCase())).toMatchInlineSnapshot(`
Map {
"AA" => {
"a": "aa",
},
"AB" => {
"a": "ab",
},
}
`)
})

test('_groupBy', () => {
expect(_groupBy(_range(5), n => (n % 2 ? 'odd' : 'even'))).toEqual({
even: [0, 2, 4],
Expand Down
23 changes: 18 additions & 5 deletions src/array/array.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,24 @@ export function _uniqBy<T>(arr: readonly T[], mapper: Mapper<T, any>): T[] {
* Returning `undefined` from the Mapper will EXCLUDE the item.
*/
export function _by<T>(items: readonly T[], mapper: Mapper<T, any>): StringMap<T> {
return items.reduce((map, item, index) => {
const res = mapper(item, index)
if (res !== undefined) map[res] = item
return map
}, {} as StringMap<T>)
return Object.fromEntries(
items.map((item, i) => [mapper(item, i), item]).filter(([k]) => k !== undefined) as [any, T][],
)
}

/**
* Map an array of items by a key, that is calculated by a Mapper.
*/
export function _mapBy<ITEM, KEY>(
items: readonly ITEM[],
mapper: Mapper<ITEM, KEY>,
): Map<KEY, ITEM> {
return new Map(
items.map((item, i) => [mapper(item, i), item]).filter(([k]) => k !== undefined) as [
KEY,
ITEM,
][],
)
}

/**
Expand Down
Loading

0 comments on commit bed09c6

Please sign in to comment.