mirror of
https://github.com/status-im/sourcecred.git
synced 2025-02-27 03:30:26 +00:00
Util: create findDuplicates (#1755)
Often we can use representations like Set to avoid duplicates in the first place. However when duplicates are not allowed in some kind of user input we may want to present them with a useful error message. This util will find the duplicate elements, so they can be highlighted in an error.
This commit is contained in:
parent
791c05e1fc
commit
757f0975f9
18
src/util/findDuplicates.js
Normal file
18
src/util/findDuplicates.js
Normal file
@ -0,0 +1,18 @@
|
||||
// @flow
|
||||
|
||||
/**
|
||||
* Finds elements in the array which are included twice or more.
|
||||
* Uses a === comparison, not deep equality.
|
||||
*/
|
||||
export function findDuplicates<T>(items: $ReadOnlyArray<T>): Set<T> {
|
||||
const encountered: Set<T> = new Set();
|
||||
const duplicates: Set<T> = new Set();
|
||||
for (const item of items) {
|
||||
if (!encountered.has(item)) {
|
||||
encountered.add(item);
|
||||
} else {
|
||||
duplicates.add(item);
|
||||
}
|
||||
}
|
||||
return duplicates;
|
||||
}
|
23
src/util/findDuplicates.test.js
Normal file
23
src/util/findDuplicates.test.js
Normal file
@ -0,0 +1,23 @@
|
||||
// @flow
|
||||
|
||||
import {findDuplicates} from "./findDuplicates";
|
||||
|
||||
describe("util/findDuplicates", () => {
|
||||
it("should work on an example", () => {
|
||||
const input = [4, 5, 1, 1, 2, 3, 4, 1];
|
||||
const duplicates = new Set([1, 4]);
|
||||
expect(findDuplicates(input)).toEqual(duplicates);
|
||||
});
|
||||
it("should not use deep comparison", () => {
|
||||
const input = [{a: true}, {a: true}, [1], [1]];
|
||||
const duplicates = new Set([]);
|
||||
expect(findDuplicates(input)).toEqual(duplicates);
|
||||
});
|
||||
it("should work with object equality", () => {
|
||||
const obj = {b: true};
|
||||
const arr = [2];
|
||||
const input = [obj, obj, arr, arr, obj];
|
||||
const duplicates = new Set([obj, arr]);
|
||||
expect(findDuplicates(input)).toEqual(duplicates);
|
||||
});
|
||||
});
|
Loading…
x
Reference in New Issue
Block a user