forked from bdefore/protondb-i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.js
116 lines (91 loc) · 2.82 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// pinched (and tweaked) from https://gomakethings.com/getting-the-differences-between-two-objects-with-vanilla-js/
/*!
* Find the differences between two objects and push to a new object
* (c) 2019 Chris Ferdinandi & Jascha Brinkmann, MIT License, https://gomakethings.com & https://twitter.com/jaschaio
* @param {Object} obj1 The original object
* @param {Object} obj2 The object to compare against it
* @return {Object} An object of differences between the two
*/
var diff = function (obj1, obj2) {
// Make sure an object to compare is provided
if (!obj2 || Object.prototype.toString.call(obj2) !== '[object Object]') {
return obj1;
}
//
// Variables
//
var diffs = {};
var key;
//
// Methods
//
/**
* Check if two arrays are equal
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Boolean} If true, both arrays are equal
*/
var arraysMatch = function (arr1, arr2) {
// Check if the arrays are the same length
if (arr1.length !== arr2.length) return false;
// Check if all items exist and are in the same order
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
// Otherwise, return true
return true;
};
/**
* Compare two items and push non-matches to object
* @param {*} item1 The first item
* @param {*} item2 The second item
* @param {String} key The key in our object
*/
var compare = function (item1, item2, key) {
// Get the object type
var type1 = Object.prototype.toString.call(item1);
var type2 = Object.prototype.toString.call(item2);
// If type2 is undefined it has been removed
if (type2 === '[object Undefined]') {
diffs[key] = 'Missing';
return;
}
// If items are different types
if (type1 !== type2) {
diffs[key] = item2;
return;
}
// If an object, compare recursively
if (type1 === '[object Object]') {
var objDiff = diff(item1, item2);
if (Object.keys(objDiff).length > 1) {
diffs[key] = objDiff;
}
return;
}
// Otherwise, just compare
if (item1 === item2 ) {
diffs[key] = `Identical to English: ${item2}`;
}
};
//
// Compare our objects
//
// Loop through the first object
for (key in obj1) {
if (obj1.hasOwnProperty(key)) {
compare(obj1[key], obj2[key], key);
}
}
// Loop through the second object and find missing items
for (key in obj2) {
if (obj2.hasOwnProperty(key)) {
if (!obj1[key] && obj1[key] !== obj2[key] ) {
diffs[key] = obj2[key];
}
}
}
// Return the object of differences
return diffs;
};
module.exports = diff