-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (61 loc) · 2.06 KB
/
Copy pathindex.js
File metadata and controls
73 lines (61 loc) · 2.06 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
const visitedObjectsSymbol = Symbol('visitedObjects')
const currentPathSymbol = Symbol('currentPath')
/*
* Public options:
* - onCircular: Function that gets called when a circular ref is discovered
*
* Private options:
* [visitedObjectsSymbol]: The list of objects already visited.
* [currentPathSymbol]: The path of the current input, as an array.
*/
module.exports = decircularize
function decircularize(input, options = {}) {
if(typeof input !== 'object' || input === null) {
return input
}
const currentPath = options[currentPathSymbol] || ['<root>']
const onCircular = options.onCircular || defaultTransform
const visitedObjects = (options[visitedObjectsSymbol] || []).concat({ path: currentPath, object: input })
if(Array.isArray(input)) {
return input.map((object, index) => {
const nextPath = currentPath.concat(index)
const circularPath = visitedObjects.find(x => x.object === object)
if(circularPath != null) {
return verifyOnCircular(circularPath, onCircular, nextPath)
}
return decircularize(object, {
[visitedObjectsSymbol]: visitedObjects,
[currentPathSymbol]: nextPath,
onCircular,
})
})
}
var output = {}
Object.keys(input).forEach(key => {
const object = input[key]
const nextPath = currentPath.concat(key)
const circularPath = visitedObjects.find(x => x.object === object)
if(circularPath != null) {
output[key] = verifyOnCircular(circularPath, onCircular, nextPath)
return
}
output[key] = decircularize(object, {
[visitedObjectsSymbol]: visitedObjects,
[currentPathSymbol]: nextPath,
onCircular,
})
})
return output
}
function verifyOnCircular(circularPath, onCircular, offendingPath) {
const result = onCircular(circularPath.object, circularPath.path, offendingPath)
if(result === circularPath.object) {
throw new Error('onCircular must not return the offending object')
}
return decircularize(result, { onCircular: () => {
throw new Error('onCircular must not return a circular structure')
} })
}
function defaultTransform(object, path) {
return `[Circular to: ${path.join('.')}]`
}