forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtojs.ts
More file actions
76 lines (71 loc) · 2.92 KB
/
Copy pathtojs.ts
File metadata and controls
76 lines (71 loc) · 2.92 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
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
72
73
74
75
76
import { isObservableArray } from "../types/observablearray"
import { isObservableObject } from "../types/observableobject"
import { isObservableMap } from "../types/observablemap"
import { isObservableValue } from "../types/observablevalue"
import { isObservable } from "./isobservable"
import { keys } from "./object-api"
export type ToJSOptions = {
detectCycles?: boolean
exportMapsAsObjects?: boolean
}
const defaultOptions: ToJSOptions = {
detectCycles: true,
exportMapsAsObjects: true
}
/**
* Basically, a deep clone, so that no reactive property will exist anymore.
*/
export function toJS<T>(source: T, options?: ToJSOptions): T
export function toJS(source: any, options?: ToJSOptions): any
export function toJS(source, options: ToJSOptions, __alreadySeen: [any, any][]) // internal overload
export function toJS(source, options?: ToJSOptions, __alreadySeen: [any, any][] = []) {
// backward compatibility
if (typeof options === "boolean") options = { detectCycles: options }
if (!options) options = defaultOptions
const detectCycles = options.detectCycles === true
// optimization: using ES6 map would be more efficient!
// optimization: lift this function outside toJS, this makes recursion expensive
function cache(value) {
if (detectCycles) __alreadySeen.push([source, value])
return value
}
if (isObservable(source)) {
if (detectCycles && __alreadySeen === null) __alreadySeen = []
if (detectCycles && source !== null && typeof source === "object") {
for (let i = 0, l = __alreadySeen.length; i < l; i++)
if (__alreadySeen[i][0] === source) return __alreadySeen[i][1]
}
if (isObservableArray(source)) {
const res = cache([])
const toAdd = source.map(value => toJS(value, options!, __alreadySeen))
res.length = toAdd.length
for (let i = 0, l = toAdd.length; i < l; i++) res[i] = toAdd[i]
return res
}
if (isObservableObject(source)) {
const res = cache({})
keys(source) // make sure we track the keys of the object
for (let key in source) {
res[key] = toJS(source[key], options!, __alreadySeen)
}
return res
}
if (isObservableMap(source)) {
if (options.exportMapsAsObjects === false) {
const res = cache(new Map())
source.forEach((value, key) => {
res.set(key, toJS(value, options!, __alreadySeen))
})
return res
} else {
const res = cache({})
source.forEach((value, key) => {
res[key] = toJS(value, options!, __alreadySeen)
})
return res
}
}
if (isObservableValue(source)) return toJS(source.get(), options!, __alreadySeen)
}
return source
}