This repository has been archived by the owner on Mar 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
diff.js
60 lines (52 loc) · 1.45 KB
/
diff.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
'use strict'
var encode = require('json8-pointer').encode
var equal = require('json8/lib/equal')
var type = require('json8/lib/type')
var ARRAY = 'array'
var OBJECT = 'object'
module.exports = function diff(a, b, pre) {
var patches = []
var prefix = pre || []
var at = type(a)
var bt = type(b)
if (bt !== at) {
if (at === undefined)
patches.push({"op": "add", "path": encode(prefix), "value": b})
else
patches.push({"op": "replace", "path": encode(prefix), "value": b})
return patches
}
else if (bt !== ARRAY && bt !== OBJECT) {
if (!equal(a, b))
patches.push({"op": "replace", "path": encode(prefix), "value": b})
return patches
}
if (a === b)
return patches
// both are arrays
if (Array.isArray(b)) {
// FIXME let's be smarter about array diffing
if (a.length === 0 && b.length === 0)
return patches
if (equal(a, b))
return patches
patches.push({"op": "replace", "path": encode(prefix), "value": b})
}
// both are objects
else if (bt === OBJECT) {
var i, l, keys, k
keys = Object.keys(b)
for (i = 0, l = keys.length; i < l; i++) {
k = keys[i]
patches = patches.concat(diff(a[k], b[k], prefix.concat([k])))
}
keys = Object.keys(a)
for (i = 0, l = keys.length; i < l; i++) {
k = keys[i]
if (b[k] !== undefined)
continue
patches.push({"op": "remove", "path": encode(prefix.concat([k]))})
}
}
return patches
}