Skip to content

Instantly share code, notes, and snippets.

@bryantee
Last active October 28, 2020 17:52
Show Gist options
  • Save bryantee/3d95da77eba5442cb66032c81528d75d to your computer and use it in GitHub Desktop.
Save bryantee/3d95da77eba5442cb66032c81528d75d to your computer and use it in GitHub Desktop.
/*
* Returns array of items de-duped based on primary key field
* ie: id
* */
function removeDuplications<T>(primaryKey: string, items: T[]): T[] {
if (items && items.length === 0) {
return [];
}
if (!items[0].hasOwnProperty(primaryKey)) {
throw new Error(`Primary key ${primaryKey} doesn't exist on the item`);
}
const uniquePrimaryKeyValues: Set<string | number> = new Set([
...items.map((item: T) => item[primaryKey]),
]);
const dedupedItems: T[] = items.filter((item: T) => {
const keyValue = item[primaryKey];
if (uniquePrimaryKeyValues.has(keyValue)) {
uniquePrimaryKeyValues.delete(keyValue);
return true;
}
return false;
});
return dedupedItems;
}
// Tests
describe('removeDuplication', function() {
const primaryKey = 'id';
const items = [
{
name: 'Bob',
id: 94,
},
{
name: 'Kim',
id: 95,
},
{
name: 'bob',
id: 94,
},
{
name: 'Nathan',
id: 100,
},
];
describe('given duplicates', function() {
it('should remove them and return', () => {
const results = removeDuplications(primaryKey, items);
expect(results).toEqual([
{
name: 'Bob',
id: 94,
},
{
name: 'Kim',
id: 95,
},
{
name: 'Nathan',
id: 100,
},
]);
});
});
describe('given no duplicate', () => {
const items = [
{
name: 'Bob',
id: 94,
},
{
name: 'Kim',
id: 95,
},
];
it('should return the same array', () => {
const results = removeDuplications(primaryKey, items);
expect(results).toEqual([
{
name: 'Bob',
id: 94,
},
{
name: 'Kim',
id: 95,
},
]);
});
});
describe("if primary key doesn't exist on array type", () => {
it('should throw an error', () => {
expect(() => removeDuplications('space_id', items)).toThrowError();
});
});
describe('if empty array is passed', () => {
it('should return an empty array', () => {
expect(removeDuplications(primaryKey, [])).toEqual([]);
expect(() => removeDuplications(primaryKey, [])).not.toThrowError();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment