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:
Robin van Boven 2020-04-23 15:04:39 +02:00 committed by GitHub
parent 791c05e1fc
commit 757f0975f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View 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;
}

View 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);
});
});