Skip to content

Commit 9fd66fc

Browse files
committed
feat(mergeMapObject): add mergeMapObject function
1 parent a6ec726 commit 9fd66fc

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

index.test.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import test from "ava";
33
import {expectType} from "ts-expect";
44
import type {Key} from "./index";
55
import {
6+
mergeMapObject,
67
copy,
78
entries,
89
excludeNullProperties,
@@ -159,6 +160,37 @@ test("mapObjectValues", t => {
159160
);
160161
});
161162

163+
test("mergeMapObject", t => {
164+
const a = {
165+
a: 1,
166+
b: 2
167+
} as const;
168+
169+
const sa = Symbol();
170+
const sb = Symbol();
171+
172+
const symbols: Record<string, symbol> = {
173+
a: sa,
174+
b: sb
175+
};
176+
177+
t.deepEqual(
178+
mergeMapObject(a, (key, value) => ({
179+
[notNull(symbols[key])]: value + 1,
180+
[`a${key}`]: value + 2,
181+
[`b${key}`]: value * 2
182+
})),
183+
{
184+
[sa]: 2,
185+
[sb]: 3,
186+
aa: 3,
187+
ab: 4,
188+
ba: 2,
189+
bb: 4
190+
}
191+
);
192+
});
193+
162194
test("filterObject", t => {
163195
const object = {
164196
a: 1,

index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,25 @@ export function mapObjectValuesFn<TObject extends object, TNewValue>(
386386
return object => mapObjectValues(object, f);
387387
}
388388

389+
/** Creates a new object by calling the specified mapping function for each
390+
* key-value pair in the specified object, and then merging the returned
391+
* objects.
392+
*
393+
* Only the string-keyed properties of the input object are considered, but
394+
* the mapping function may produce keys of any suitable type.
395+
*
396+
* If the mapping function returns multiple objects that have the same key,
397+
* then later values will overwrite earlier ones. */
398+
export function mergeMapObject<TObject extends object, TNewKey extends Key, TNewValue>(
399+
object: Readonly<TObject>,
400+
f: (
401+
key: StringKey<TObject>,
402+
value: StringKeyedValue<TObject>
403+
) => Readonly<Record<TNewKey, TNewValue>>
404+
): Record<TNewKey, TNewValue> {
405+
return mergeRecords(map(entries(object), ([key, value]) => f(key, value)));
406+
}
407+
389408
/** Creates a new object that contains the string-keyed properties of the
390409
* specified object, filtered by the specified predicate. */
391410
export function filterObject<T extends object>(

0 commit comments

Comments
 (0)