-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
76 lines (68 loc) · 1.46 KB
/
utils.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
72
73
74
75
module.exports = {
toMap: toMap,
fromMap: fromMap,
areq: areq,
cBind: cBind,
cEqual: cEqual,
dump: dump
}
function dump(manager, data) {
var map = toMap(data)
for (var id in map) {
manager.set(id, map[id])
}
}
function areq(a, b) {
if (a.length != b.length) return false
for (var i=0; i<a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
function cBind(fn) {
var args = [].slice.call(arguments, 1)
, f = fn.bind.apply(fn, args)
f.args = args
f.orig = fn
return f
}
function cEqual(f1, f2) {
if (f1.orig !== f2.orig) return false
return areq(f1.args, f2.args)
}
function toMap(data) {
var map = {}
, children = []
, cmap
map[data.id] = {
children: children,
open: true
}
if (data.data) map[data.id].data = data.data
if (!data.children) return map
for (var i=0; i<data.children.length; i++) {
children.push(data.children[i].id)
cmap = toMap(data.children[i])
for (var name in cmap) {
map[name] = cmap[name]
}
}
return map
}
function fromMap(root, map, hits) {
var node = map[root]
, tree = {
id: root,
open: true
}
hits = hits || {}
if (hits[root]) throw new Error('Hit a node twice: ' + root)
hits[root] = true
if (node.data) tree.data = node.data
if (!node.children.length) return tree
tree.children = []
for (var i=0; i<node.children.length; i++) {
tree.children.push(fromMap(node.children[i], map, hits))
}
return tree
}