Created
March 3, 2020 20:39
-
-
Save miguel-leon/54152daeef8c026d340d50b3e96e923d to your computer and use it in GitHub Desktop.
array uniques
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { uniques, uniquesByAtt } from './uniques'; | |
describe('uniques function', () => { | |
it('should filter unique elements by strict equality by default', () => { | |
const value = [1, 2, 3, 3, 2, 1, 4, 5, 5]; | |
const res = uniques(value); | |
expect(res).toEqual([1, 2, 3, 4, 5]); | |
}); | |
it('should filter unique elements using comparator function', () => { | |
const value = [{ a: 3 }, { a: 2 }, { a: 5 }, { a: 2 }]; | |
const res = uniquesByAtt(value, 'a'); | |
expect(res).toEqual([{ a: 3 }, { a: 2 }, { a: 5 }]); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function uniques(array: any[], comp: (a: any, b: any) => boolean = (a, b) => a === b) { | |
const len = array.length, res = new Array(len); | |
let c = 0; | |
function fresh(value: any) { | |
for (let j = 0; j < c; j++) { | |
if (comp(value, res[j])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
for (let i = 0; i < len; i++) { | |
if (fresh(array[i])) { | |
res[c++] = array[i]; | |
} | |
} | |
res.length = c; | |
return res; | |
} | |
export function uniquesByAtt<K extends string>(array: Array<{ [k in K]: any }>, att: K) { | |
return uniques(array, (a, b) => a[att] === b[att]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment