Skip to content
This repository was archived by the owner on Nov 9, 2024. It is now read-only.

Commit 9966d93

Browse files
authored
fix: uniqueByShape util (#294)
* fix: uniqueByShape util * test: add dupe test
1 parent a6c060c commit 9966d93

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

src/utils.js

+30-3
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,42 @@ export function toDataAttributes(attrs) {
3232
return dataAttrs;
3333
}
3434

35+
function deepEqual(x, y) {
36+
if (x === y) {
37+
return true;
38+
} else if (
39+
typeof x === 'object' &&
40+
x != null &&
41+
typeof y === 'object' &&
42+
y != null
43+
) {
44+
if (Object.keys(x).length !== Object.keys(y).length) {
45+
return false;
46+
}
47+
48+
for (const prop in x) {
49+
if (y.hasOwnProperty(prop)) {
50+
if (!deepEqual(x[prop], y[prop])) {
51+
return false;
52+
}
53+
} else {
54+
return false;
55+
}
56+
}
57+
58+
return true;
59+
} else {
60+
return false;
61+
}
62+
}
63+
3564
export function uniqueByShape(arr) {
3665
const output = [];
37-
const lookup = Object.create(null);
3866

3967
arr.forEach(item => {
40-
if (lookup[JSON.stringify(item)] === undefined) {
68+
if (!output.find(outputItem => deepEqual(item, outputItem))) {
4169
output.push(item);
4270
}
43-
lookup[JSON.stringify(item)] = true;
4471
});
4572

4673
return output;

test/utils.test.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
import {uniqueByShape} from '../src/utils';
22

3+
const date = new Date();
4+
const element = document.body;
5+
36
describe('uniqueByShape', () => {
47
it('filters duplicates', () => {
58
expect(
69
uniqueByShape([
710
{name: 'hello'},
811
{name: 'hello'},
9-
{name: 'hello', enabled: false},
12+
{name: 'hello', enabled: false, options: {date, element}},
13+
{name: 'hello', enabled: false, options: {date, element}},
14+
{name: 'hello', options: {element, x: true}},
1015
{name: 'hello2'},
1116
]),
1217
).toEqual([
1318
{name: 'hello'},
14-
{name: 'hello', enabled: false},
19+
{name: 'hello', enabled: false, options: {date, element}},
20+
{name: 'hello', options: {x: true, element}},
1521
{name: 'hello2'},
1622
]);
1723
});

0 commit comments

Comments
 (0)