Skip to content

Commit 64f6e9c

Browse files
committed
Keep a stack of ancestor keys.
1 parent d150621 commit 64f6e9c

File tree

1 file changed

+7
-17
lines changed

1 file changed

+7
-17
lines changed

stringify.js

+7-17
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
var has = Object.hasOwnProperty
21
exports = module.exports = stringify
32
exports.getSerialize = serializer
43

@@ -7,35 +6,26 @@ function stringify(obj, replacer, spaces, cycleReplacer) {
76
}
87

98
function serializer(replacer, cycleReplacer) {
10-
var stack = []
9+
var stack = [], keys = []
1110

1211
if (cycleReplacer == null) cycleReplacer = function(key, value) {
13-
return pathize(stack, key, value)
12+
return pathize(stack, keys, value)
1413
}
1514

1615
return function(key, value) {
1716
if (stack.length > 0) {
1817
var thisPos = stack.indexOf(this)
1918
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
19+
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
2020
if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
2121
}
2222
else stack.push(value)
2323

24-
return replacer ? replacer.call(this, key, value) : value
24+
return replacer == null ? value : replacer.call(this, key, value)
2525
}
2626
}
2727

28-
function pathize(stack, key, value) {
29-
var paths = [""]
30-
31-
for (var i = 0, l = stack.indexOf(value); i < l; ++i)
32-
paths.push(findKey(stack[i], stack[i + 1]))
33-
34-
return "[Circular ~" + paths.join(".") + "]"
35-
}
36-
37-
function findKey(obj, value) {
38-
// For arrays from foreign context, for-in will probably do.
39-
if (obj instanceof Array) return obj.indexOf(value)
40-
for (var key in obj) if (has.call(obj, key) && obj[key] === value) return key
28+
function pathize(stack, keys, value) {
29+
if (stack[0] === value) return "[Circular ~]"
30+
return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
4131
}

0 commit comments

Comments
 (0)