Skip to content

Commit eb6fe4f

Browse files
committed
Support array replacer (fixes moll#14)
1 parent 5930d6e commit eb6fe4f

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

stringify.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ function stringify(obj, replacer, spaces, cycleReplacer) {
66
}
77

88
function serializer(replacer, cycleReplacer) {
9-
var stack = [], keys = []
9+
var stack = [], keys = [], replacerArray = Array.isArray(replacer)
1010

1111
if (cycleReplacer == null) cycleReplacer = function(key, value) {
1212
if (stack[0] === value) return "[Circular ~]"
@@ -15,13 +15,17 @@ function serializer(replacer, cycleReplacer) {
1515

1616
return function(key, value) {
1717
if (stack.length > 0) {
18+
if (replacerArray && replacer.indexOf(key) === -1) {
19+
return
20+
}
21+
1822
var thisPos = stack.indexOf(this)
1923
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
2024
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
2125
if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
2226
}
2327
else stack.push(value)
2428

25-
return replacer == null ? value : replacer.call(this, key, value)
29+
return replacer == null || replacerArray ? value : replacer.call(this, key, value)
2630
}
2731
}

test/stringify_test.js

+33
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,39 @@ describe("Stringify", function() {
156156
replacer.args[2][1].must.equal("[Circular ~]")
157157
})
158158

159+
it("must support array replacer", function() {
160+
var obj = {name: "Alice", child: {name: "Bob", "": "Carol"}, "": "Dan"}
161+
obj.child.self = obj.child
162+
163+
stringify(obj, ["name"], 2).must.eql(jsonify({
164+
name: "Alice"
165+
}))
166+
167+
stringify(obj, ["name", ""], 2).must.eql(jsonify({
168+
name: "Alice",
169+
"": "Dan"
170+
}))
171+
172+
stringify(obj, ["child"], 2).must.eql(jsonify({
173+
child: {}
174+
}))
175+
176+
stringify(obj, ["child", ""], 2).must.eql(jsonify({
177+
child: {
178+
"": "Carol"
179+
},
180+
"": "Dan"
181+
}))
182+
183+
stringify(obj, ["child", "", "self"], 2).must.eql(jsonify({
184+
child: {
185+
"": "Carol",
186+
self: "[Circular ~.child]"
187+
},
188+
"": "Dan"
189+
}))
190+
})
191+
159192
it("must call given decycler and use its output for nested objects",
160193
function() {
161194
var obj = {}

0 commit comments

Comments
 (0)