-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.ts
33 lines (30 loc) · 966 Bytes
/
transform.ts
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
// SPDX-License-Identifier: MPL-2.0
import type Distree from "./Distree.ts"
import from from "./from.ts"
import insert from "./insert.ts"
/**
* Transforms the values of the given distree. It does not modify the passed distree, and instead returns a new distree with the transformed values.
*
* If `transformer` throws `undefined`, the value will be filtered out from the result.
*
* @param distree The distree the result based on.
* @param transformer The function that transforms the values.
* @returns A new distree with the transformed values.
*/
const transform = <T, U>(
distree: Distree<T>,
transformer: (value: T, path: string) => Distree.ItemInitializer<U>,
): Distree<U> => {
return [...distree]
.map(([path, value]) => {
try {
return [[path, transformer(value, path)] as const]
} catch (error) {
if (error === undefined) return []
else throw error
}
})
.flat()
.reduce(insert, from({}))
}
export default transform