-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (67 loc) · 1.8 KB
/
index.js
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
66
67
68
69
70
71
/* @flow strict */
import type { Collection } from "immutable";
/**
* A handy memoizer for nested Immutable.js transformations - helps to avoid
* expensive tree traversal and object re-creation during frequent .toJS calls
*/
export default function memoizeImmutableTransform (
transformEntities: any => any,
targetCollection?: "same" | "object" | "array" | "list" | "map" | "seq"
) {
let preTransform = null;
let postTransform = null;
switch (targetCollection) {
case "array":
preTransform = v => v.valueSeq();
postTransform = v => v.toArray();
break;
case "object":
preTransform = v => v.toKeyedSeq();
postTransform = v => v.toObject();
break;
case "list":
preTransform = v => v.valueSeq();
postTransform = v => v.toList();
break;
case "map":
preTransform = v => v.toKeyedSeq();
postTransform = v => v.toMap();
break;
case "seq":
preTransform = v => v.toSeq();
postTransform = v => v;
break;
case "same":
default:
preTransform = postTransform = v => v;
break;
}
const cache = new WeakMap();
function mapContents (valueObj) {
if (valueObj === null || valueObj === undefined) {
return valueObj;
}
const cached = cache.get(valueObj);
if (cached) {
return cached;
}
const transformedObj = transformEntities(valueObj);
cache.set(valueObj, transformedObj);
return transformedObj;
}
return function memoizedImmutableTransform (
valueObj: Collection.Indexed<any> | Collection.Keyed<any, any>
) {
if (valueObj === null || valueObj === undefined) {
return valueObj;
}
const cached = cache.get(valueObj);
if (cached) {
return cached;
}
const mappedValueObj = preTransform(valueObj).map(mapContents);
const transformedObj = postTransform(mappedValueObj);
cache.set(valueObj, transformedObj);
return transformedObj;
};
}