/
map-vals.ts
52 lines (51 loc) · 1.46 KB
/
map-vals.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import type { Fn, IObjectOf } from "@thi.ng/api";
import type { Transducer } from "../api";
import { $iter } from "../iterator";
import { map } from "./map";
/**
* Transducer. Similar to {@link (map:1)}, but expects object values and
* the given function `fn` is applied to each enumerable property value
* and the results reassigned to their original keys.
*
* @remarks
* By default, a shallow copy of the source object is created. The
* resulting object is then used as the result of this transducer.
*
* @example
* ```ts
* [...mapVals((x)=> x * 10, [{a: 1, b: 2}, {c: 3, d: 4}])]
* // [ { a: 10, b: 20 }, { c: 30, d: 40 } ]
* ```
*
* @param fn -
* @param copy - if true (default), creates a shallow copy of each
* incoming value
*/
export function mapVals<A, B>(
fn: Fn<A, B>,
copy?: boolean
): Transducer<IObjectOf<A>, IObjectOf<B>>;
export function mapVals<A, B>(
fn: Fn<A, B>,
src: Iterable<IObjectOf<A>>
): IterableIterator<IObjectOf<B>>;
export function mapVals<A, B>(
fn: Fn<A, B>,
copy: boolean,
src: Iterable<IObjectOf<A>>
): IterableIterator<IObjectOf<B>>;
export function mapVals<A, B>(...args: any[]): any {
const iter = $iter(mapVals, args);
if (iter) {
return iter;
}
const fn: Fn<A, B> = args[0];
const copy = args[1] !== false;
return map((x: any) => {
const res: any = copy ? {} : x;
for (let k in x) {
res[k] = fn(x[k]);
}
return <any>res;
});
}