Skip to content

Commit 740dcdf

Browse files
committed
Add undefinedReplacement option to diffJson
1 parent 870aa15 commit 740dcdf

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

Diff for: src/diff/json.js

+21-2
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,33 @@ jsonDiff.useLongestToken = true;
1111

1212
jsonDiff.tokenize = lineDiff.tokenize;
1313
jsonDiff.castInput = function(value) {
14-
return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), undefined, ' ');
14+
const {undefinedReplacement} = this;
15+
16+
return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function(k, v) {
17+
if (typeof v === 'undefined') {
18+
return undefinedReplacement;
19+
}
20+
21+
return v;
22+
}, ' ');
1523
};
1624
jsonDiff.equals = function(left, right) {
1725
return Diff.prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
1826
};
1927

20-
export function diffJson(oldObj, newObj, callback) { return jsonDiff.diff(oldObj, newObj, callback); }
28+
export function diffJson(oldObj, newObj, options, callback) {
29+
if (typeof options === 'function') {
30+
callback = options;
31+
options = {};
32+
}
2133

34+
if (typeof options === 'undefined') {
35+
options = {};
36+
}
37+
38+
jsonDiff.undefinedReplacement = options.undefinedReplacement;
39+
return jsonDiff.diff(oldObj, newObj, callback);
40+
}
2241

2342
// This function handles the presence of circular references by bailing out when encountering an
2443
// object that is already on the "stack" of items being processed.

Diff for: test/diff/json.js

+21
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,27 @@ describe('diff/json', function() {
6666
)).to.eql([
6767
{ count: 4, value: '{\n "a": 123,\n "b": 456\n}' }
6868
]);
69+
expect(diffJson(
70+
{a: 123, b: 456, c: undefined},
71+
{a: 123, b: 456},
72+
{undefinedReplacement: null}
73+
)).to.eql([
74+
{ count: 3, value: '{\n "a": 123,\n "b": 456,\n' },
75+
{ count: 1, value: ' "c": null\n', added: undefined, removed: true },
76+
{ count: 1, value: '}' }
77+
]);
78+
});
79+
80+
it('should handle callback', function(done) {
81+
diffJson(
82+
{},
83+
{},
84+
function(err, result) {
85+
expect(err).to.be.undefined;
86+
expect(result).to.eql([{ count: 1, value: '{}' }]);
87+
done();
88+
}
89+
);
6990
});
7091

7192
it('should accept already stringified JSON', function() {

0 commit comments

Comments
 (0)