Last active
April 11, 2018 00:13
-
-
Save DrRobotmck/7a8a04eeac4e8ff6eafeccea155d70f9 to your computer and use it in GitHub Desktop.
Duplicate checker
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
const a = [10,20,30,40]; | |
const b = [10,10,20,30,40]; | |
const c = [10,10,20,20,30,30]; | |
const d = [10,10,20,20,30,30,40,10]; | |
const benchmark = [...a, ...b, ...c, ...d]; | |
/* | |
Using two for loops | |
- first loop will determine which values are actually duplicates in the array | |
- second loop iterates across the object counting the number of duplicates | |
*/ | |
function hasDupes(input) { | |
let count = 0; | |
const holder = {}; | |
for (let i = 0; i < input.length; i++) { | |
const currVal = input[i]; | |
holder[currVal] = holder[currVal] !== undefined; | |
} | |
for (let value in holder) { | |
if (holder[value]) count++; | |
} | |
return count; | |
} | |
console.time('first'); | |
hasDupes(benchmark); | |
console.timeEnd('first'); | |
/* | |
Using forEach | |
- eliminates need for a second for loop/uses `.forEach` | |
- BUT -> `.lastIndexOf` has to check all of the values of the array | |
on each iteration of the loop to determine if there is a duplicate | |
- slightly more concise | |
*/ | |
function hasDupesForEach(input) { | |
let count = 0; | |
const holder = {}; | |
input.forEach((val, idx, inputArr) => { | |
if ( | |
inputArr.lastIndexOf(val) !== idx && | |
!holder[val] | |
) count++ | |
holder[val] = true; | |
}); | |
return count; | |
} | |
console.time('second'); | |
hasDupesForEach(benchmark); | |
console.timeEnd('second'); | |
/* | |
Using reduce | |
- no counter necessary | |
- no holder object needed (technically the accumulator for reduce is the holder) | |
- complicated, kinda hard to understand what it is actually doing. | |
*/ | |
function hasDupesReduce(input) { | |
return input.reduce((accumulator, currentValue, index) => { | |
if ( | |
input.lastIndexOf(currentValue) !== index && | |
accumulator[currentValue] === undefined | |
) { | |
accumulator.count++; | |
} | |
accumulator[currentValue] = true; | |
return accumulator; | |
}, { count: 0 }).count | |
} | |
console.time('third'); | |
hasDupesReduce(benchmark); | |
console.timeEnd('third'); | |
/* | |
console.log(hasDupes(a)); | |
console.log(hasDupes(b)); | |
console.log(hasDupes(c)); | |
console.log(hasDupes(d)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment