-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
mapProperties.ts
22 lines (21 loc) · 860 Bytes
/
mapProperties.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import type { AnyRecord } from './any_record.js'
import { reduceByKey } from './reduceKey.js'
import type { ValueOf } from './ValueOf.js'
/**
* An Object-specific version of `map`.
* Original source:
* <https://stackoverflow.com/questions/53964071/how-to-dynamically-create-mapped-type-in-typescript>
*
* `ramda` has a similar function (`mapObjIndexed()`) with different parameter order.
* I keep this parameter order because this parameter order provides better type inference.
*/
export function mapProperties<Subject extends AnyRecord, ResultProp>(
subject: Subject,
callbackfn: (value: ValueOf<Subject>, key: keyof Subject, obj: Subject) => ResultProp
): { [K in keyof Subject]: ResultProp } {
return reduceByKey(
subject,
(p, key) => ((p[key] = callbackfn(subject[key], key, subject)), p),
{} as { [K in keyof Subject]: ResultProp }
)
}