-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
88 lines (79 loc) · 2 KB
/
index.js
File metadata and controls
88 lines (79 loc) · 2 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
/**
* @license shallow-diff https://github.com/cosmosio/shallow-diff
*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Olivier Scherrer <[email protected]>
*/
"use strict";
function assert(assertion, error) {
if (assertion) {
throw new TypeError("simple-loop: " + error);
}
}
var loop = require("simple-loop");
/**
* Make a diff between two objects
* @param {Array/Object} base the base object
* @param {Array/Object} compared the object to compare the base with
* @example:
* With objects:
*
* base = {a:1, b:2, c:3, d:4, f:6}
* compared = {a:1, b:20, d: 4, e: 5}
* will return :
* {
* unchanged: ["a", "d"],
* updated: ["b"],
* deleted: ["f"],
* added: ["e"]
* }
*
* It also works with Arrays:
*
* base = [10, 20, 30]
* compared = [15, 20]
* will return :
* {
* unchanged: [1],
* updated: [0],
* deleted: [2],
* added: []
* }
*
* @returns object
*/
module.exports = function shallowDiff(base, compared) {
assert(typeof base != "object", "the first object to compare with shallowDiff needs to be an object");
assert(typeof compared != "object", "the second object to compare with shallowDiff needs to be an object");
var unchanged = [],
updated = [],
deleted = [],
added = [];
// Loop through the compared object
loop(compared, function(value, idx) {
// To get the added items
if (!(idx in base)) {
added.push(idx);
// The updated items
} else if (value !== base[idx]) {
updated.push(idx);
// And the unchanged
} else if (value === base[idx]) {
unchanged.push(idx);
}
});
// Loop through the before object
loop(base, function(value, idx) {
// To get the deleted items
if (!(idx in compared)) {
deleted.push(idx);
}
});
return {
updated: updated,
unchanged: unchanged,
added: added,
deleted: deleted
};
};