Last active
September 21, 2016 23:25
-
-
Save mgtitimoli/06b5ac717607000bcf77760177a105c7 to your computer and use it in GitHub Desktop.
Duplicates
This file contains hidden or 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
const not = fn => (...args) => !fn(...args); | |
const notEqual = (v1, v2) => !Object.is(v1, v2); | |
const withDuplicates = (filterIndex, arr, isEqual = Object.is) => arr.filter( | |
(filteredValue, filteredIndex) => filterIndex( | |
filteredIndex, | |
arr.findIndex(curValue => isEqual(curValue, filteredValue)) | |
) | |
); | |
const getDuplicates = (arr, isEqual) => withDuplicates(notEqual, arr, isEqual); | |
const getUniques = (arr, isEqual) => withDuplicates(Object.is, arr, isEqual); | |
const isFirstOrNotEqPrev = (arr, compareFn, value, index) => | |
index === 0 || compareFn(value, arr[index - 1]) !== 0; | |
const isNotLastAndEqNext = (arr, compareFn, value, index) => | |
index < arr.length - 1 && compareFn(value, arr[index + 1]) === 0; | |
const getDuplicatesFilter = (arr, compareFn) => (value, index) => | |
isFirstOrNotEqPrev(arr, compareFn, value, index) | |
&& isNotLastAndEqNext(arr, compareFn, value, index); | |
const getUniquesFilter = (arr, compareFn) => | |
not(getDuplicatesFilter(arr, compareFn)); | |
const getDuplicatesFaster = (arr, compareFn) => ( | |
arr.length < 2 ? | |
[] : | |
arr | |
.sort(compareFn) | |
.filter(getDuplicatesFilter(arr, compareFn)) | |
); | |
const getUniquesFaster = (arr, compareFn) => ( | |
arr.length < 2 ? | |
Array.from(arr) : | |
arr | |
.sort(compareFn) | |
.filter(getUniquesFilter(arr, compareFn)) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment