Last active
February 17, 2025 09:29
-
-
Save leipreachan/0af29a8f5c25eab8dd28fd741966d39b to your computer and use it in GitHub Desktop.
different solutions to check for 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 hasDuplicateOneline = (array) => | |
new Set(array).size != array.length; | |
const hasDuplicateAlternative = (arr) => | |
arr.some((value, index, origin) => origin.indexOf(value) !== index); | |
let z = []; | |
for (let i = 0; i < 10_000; i++) { | |
z.push(i); | |
} | |
// z.push(1); | |
const testFunctions = [hasDuplicateOneline, hasDuplicateAlternative]; | |
let start, stop, avg, execTime = {}; | |
for (let index in testFunctions) { | |
const func = testFunctions[index]; | |
execTime[func.name] = []; | |
for (let j=0; j<1000; j++) { | |
performance.mark('start'); | |
testFunctions[index](z); | |
performance.mark('stop'); | |
performance.measure('executionTime', 'start', 'stop'); | |
execTime[func.name].push(performance.getEntriesByName('executionTime')[0].duration); | |
} | |
performance.clearMarks(); | |
performance.clearMeasures(); | |
} | |
console.log(`${z.length} elements:`); | |
for (let index in testFunctions) { | |
const func = testFunctions[index]; | |
avg = execTime[func.name].reduce((prev, cur) => {return prev + cur}, 0) / execTime[func.name].length; | |
console.log(`${func.name} ${execTime[func.name].length} runs avg: ${avg}`); | |
} |
Author
leipreachan
commented
Feb 16, 2025
$ node simple.js
10001 elements:
hasDuplicateOneline 100 runs avg: 0.42
hasDuplicateAlternative 100 runs avg: 10.52
$ bun -version
1.2.2
laptop:~/workspace/tempproject
$ node --version
v23.7.0
Set
has size
property, not length
. The current version
const hasDuplicateOneline = (array) =>
new Set(array).length != array.length;
is evaluating undefined != array.length
.
That is currently
hasDuplicateOneline([1,2,3]) // true
evaluates to true
, which is incorrect.
Should be
var hasDuplicateOneline = (array) =>
new Set(array).size != array.length;
hasDuplicateOneline([1,2,3]) // false
Set
hassize
property, notlength
. The current versionconst hasDuplicateOneline = (array) => new Set(array).length != array.length;
is evaluating
undefined != array.length
.That is currently
hasDuplicateOneline([1,2,3]) // true
evaluates to
true
, which is incorrect.Should be
var hasDuplicateOneline = (array) => new Set(array).size != array.length;
hasDuplicateOneline([1,2,3]) // false
well pointed, I updated the code. Yet the difference is still noticeable
$ node simple.js
10000 elements:
hasDuplicateOneline 1000 runs avg: 0.6117080000000104
hasDuplicateAlternative 1000 runs avg: 10.793499999999812
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment