-
Notifications
You must be signed in to change notification settings - Fork 24
/
equal.ts
80 lines (62 loc) · 1.83 KB
/
equal.ts
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
import curry from '../function/curry';
import isArray from './array';
const isEqualNativeTypes = (test1, test2) => test1.toString() === test2.toString();
const isEqualArrays = (test1, test2) => {
const len = test1.length;
if (len !== test2.length) {
return false;
}
for (let i = 0; i < len; i++) {
if (!isEqual(test1[i], test2[i])) {
return false;
}
}
return true;
};
const isEqualObjects = (test1, test2) => {
const keys = Object.keys(test1);
const len = keys.length;
if (len !== Object.keys(test2).length) {
return false;
}
for (let i = 0; i < len; i++) {
const key = keys[i];
if (!(Object.prototype.hasOwnProperty.call(test2, key) && isEqual(test1[key], test2[key]))) {
return false;
}
}
return true;
};
/**
* Returns `true` if its arguments are equivalent, `false` otherwise.
*
* @param {*} test1
* @param {*} test2
* @return {Boolean}
* @example
*
* isEqual(1, 1); //=> true
* isEqual(1, '1'); //=> false
* isEqual([1, 2, 3], [1, 2, 3]); //=> true
* isEqual({ a: { b: 1 }}, { a: { b: 1 }}); //=> true
*/
const isEqual = (test1, test2): boolean => {
if (test1 === test2) {
return true;
}
if (typeof test1 !== typeof test2 || test1 !== Object(test1) || !test1 || !test2) {
return false;
}
if (isArray(test1) && isArray(test2)) {
return isEqualArrays(test1, test2);
}
const test1ToString = Object.prototype.toString.call(test1);
if (test1ToString === '[object Object]' && Object.prototype.toString.call(test2) === test1ToString) {
return isEqualObjects(test1, test2);
}
if (typeof test1 === 'function') {
return test1 === test2;
}
return isEqualNativeTypes(test1, test2);
};
export default curry(isEqual);