forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.ts
More file actions
36 lines (33 loc) · 1.2 KB
/
objects.ts
File metadata and controls
36 lines (33 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export function mapValues<T, U>(
input: Record<string, T>,
mapper: (value: T) => U,
): Record<string, U> {
return mapEntries(input, (k, v) => [k, mapper(v)]);
}
export function mapEntries<T, U>(
input: Record<string, T>,
mapper: (key: string, val: T) => [key: string, val: U],
): Record<string, U> {
// Direct assignment is faster than Object.fromEntries()
// https://github.com/rocicorp/mono/pull/3927#issuecomment-2706059475
const output: Record<string, U> = {};
// In chrome Object.entries is faster than for-in (13x) or Object.keys (15x)
// https://gist.github.com/arv/1b4e113724f6a14e2d4742bcc760d1fa
for (const entry of Object.entries(input)) {
const mapped = mapper(entry[0], entry[1]);
output[mapped[0]] = mapped[1];
}
return output;
}
export function mapAllEntries<T, U>(
input: Record<string, T>,
mapper: (entries: [key: string, val: T][]) => [key: string, val: U][],
): Record<string, U> {
// Direct assignment is faster than Object.fromEntries()
// https://github.com/rocicorp/mono/pull/3927#issuecomment-2706059475
const output: Record<string, U> = {};
for (const mapped of mapper(Object.entries(input))) {
output[mapped[0]] = mapped[1];
}
return output;
}