circular.js
2.88 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var assert = require('assert');
var Traverse = require('traverse');
var util = require('util');
exports.circular = function () {
var obj = { x : 3 };
obj.y = obj;
var foundY = false;
Traverse(obj).forEach(function (x) {
if (this.path.join('') == 'y') {
assert.equal(
util.inspect(this.circular.node),
util.inspect(obj)
);
foundY = true;
}
});
assert.ok(foundY);
};
exports.deepCirc = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
var times = 0;
Traverse(obj).forEach(function (x) {
if (this.circular) {
assert.deepEqual(this.circular.path, []);
assert.deepEqual(this.path, [ 'y', 2 ]);
times ++;
}
});
assert.deepEqual(times, 1);
};
exports.doubleCirc = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var circs = [];
Traverse(obj).forEach(function (x) {
if (this.circular) {
circs.push({ circ : this.circular, self : this, node : x });
}
});
assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]);
assert.deepEqual(circs[0].circ.path, []);
assert.deepEqual(circs[1].self.path, [ 'y', 2 ]);
assert.deepEqual(circs[1].circ.path, []);
assert.deepEqual(circs.length, 2);
};
exports.circDubForEach = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
Traverse(obj).forEach(function (x) {
if (this.circular) this.update('...');
});
assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] });
};
exports.circDubMap = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var c = Traverse(obj).map(function (x) {
if (this.circular) {
this.update('...');
}
});
assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] });
};
exports.circClone = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var clone = Traverse.clone(obj);
assert.ok(obj !== clone);
assert.ok(clone.y[2] === clone);
assert.ok(clone.y[2] !== obj);
assert.ok(clone.x[3][2] === clone);
assert.ok(clone.x[3][2] !== obj);
assert.deepEqual(clone.x.slice(0,3), [1,2,3]);
assert.deepEqual(clone.y.slice(0,2), [4,5]);
};
exports.circMapScrub = function () {
var obj = { a : 1, b : 2 };
obj.c = obj;
var scrubbed = Traverse(obj).map(function (node) {
if (this.circular) this.remove();
});
assert.deepEqual(
Object.keys(scrubbed).sort(),
[ 'a', 'b' ]
);
assert.ok(Traverse.deepEqual(scrubbed, { a : 1, b : 2 }));
assert.equal(obj.c, obj);
};