-
Notifications
You must be signed in to change notification settings - Fork 6
/
deep-map.ts
65 lines (50 loc) · 1.33 KB
/
deep-map.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
53
54
55
56
57
58
59
60
61
62
63
64
65
import WeakMap = require('es6-weak-map');
import {isArray, isObject} from 'lodash';
interface NonPrimitive extends Object {
[key: string]: any;
[index: number]: any;
}
export interface MapFn {
(value: any, key: string|number): any;
}
export interface Opts {
thisArg?: any;
inPlace?: boolean;
}
export class DeepMap {
private cache = new WeakMap<NonPrimitive, any>();
constructor(
private mapFn: MapFn,
private opts: Opts
) { }
public map(value: any, key?: string|number): any {
return isArray(value) ? this.mapArray(value) :
isObject(value) ? this.mapObject(value) :
this.mapFn.call(this.opts.thisArg, value, key);
}
private mapArray(arr: any[]): any[] {
if (this.cache.has(arr)) {
return this.cache.get(arr);
}
let length = arr.length;
let result = this.opts.inPlace ? arr : [];
this.cache.set(arr, result);
for (let i = 0; i < length; i++) {
result[i] = this.map(arr[i], i);
}
return result;
}
private mapObject(obj: NonPrimitive): NonPrimitive {
if (this.cache.has(obj)) {
return this.cache.get(obj);
}
let result = this.opts.inPlace ? obj : {};
this.cache.set(obj, result);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = this.map(obj[key], key);
}
}
return result;
}
}