-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathobject-shallow-compare.js
More file actions
117 lines (94 loc) · 2.44 KB
/
Copy pathobject-shallow-compare.js
File metadata and controls
117 lines (94 loc) · 2.44 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
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
117
const nObjects = 64
const nKeys = PROCESS_ARGS[1] ? +PROCESS_ARGS[1] : 15
const generateKey = PROCESS_ARGS[2] === 'same-shape' ? (index) => index : () => Math.random()
const generateValue = PROCESS_ARGS[3] === 'same-values' ? (index) => index : () => Math.random()
function generateMono(nKeys) {
return Array.from({ length: nObjects }).map(() =>
Array.from({ length: nKeys }).reduce((acc, curr, index) => {
acc['key' + generateKey(index)] = generateValue(index)
return acc
}, {})
)
}
const inputs = generateMono(nKeys)
function shallowDiffers(a, b) {
for (let i in a) if (i !== '__source' && !(i in b)) return true;
for (let i in b) if (i !== '__source' && a[i] !== b[i]) return true;
return false;
}
function shallowDiffers_reverse(a, b) {
for (let i in a) if (i !== '__source' && a[i] !== b[i]) return true;
for (let i in b) if (i !== '__source' && !(i in a)) return true;
return false;
}
function fastObjectShallowEqual(a, b) {
let aLength = 0;
let bLength = 0;
for (const key in a) {
if (key === '__source') { continue }
aLength += 1;
if (a[key] !== b[key]) {
return false;
}
if (!(key in b)) {
return false;
}
}
for (const key in b) {
if (key === '__source') { continue }
bLength += 1;
}
return aLength === bLength;
}
export default {
blocks: [
{
id: 'shallowDiffers',
setup: () => {
const a = inputs[0]
return () => {
let result = 0
for (let i = 0; i < inputs.length - 1; i++) {
const b = inputs[i]
if (!shallowDiffers(a, b)) {
result += 1
}
}
return result
}
}
},
{
id: 'shallowDiffers_reverse',
setup: () => {
const a = inputs[0]
return () => {
let result = 0
for (let i = 0; i < inputs.length - 1; i++) {
const b = inputs[i]
if (!shallowDiffers_reverse(a, b)) {
result += 1
}
}
return result
}
}
},
{
id: 'fastObjectShallowEqual',
setup: () => {
const a = inputs[0]
return () => {
let result = 0
for (let i = 0; i < inputs.length - 1; i++) {
const b = inputs[i]
if (fastObjectShallowEqual(a, b)) {
result += 1
}
}
return result
}
}
},
]
}