-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrays-equal.js
46 lines (40 loc) · 1.09 KB
/
arrays-equal.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
// Source: https://jsperf.com/comparing-arrays2/3
function arraysEqual(array1, array2) {
const a = array1;
const b = array2;
const c = a.length !== b.length;
/*
* Test both factors that immediately make this method unnecessary.
*/
if (c || !b) {
return false;
}
/*
* Assign the length value to a variable outside of the loop to
* increase performance. The process is sped up because the value is
* not being evaluated every time the decrement loop is being run.
*/
let i = a.length;
/*
* Use a decrement to iterate through the array objects.
*/
for (i; i--; ) {
/*
* Compare the objects types for arrays. If both are arrays then
* loop through this function again with those objects.
*/
if (a[i] instanceof Array && a[i] instanceof Array) {
/*
* Recursively run the same test to determine if the child objects
* are equal arrays.
*/
if (!arraysEqual(a[i], b[i])) {
return false;
}
} else if (a[i] !== b[i]) {
return false;
}
}
return true;
}
module.exports = { arraysEqual };