Test name | Executions per second |
---|---|
Set With For Loop | 0.3 Ops/sec |
Sort With For Loop | 387.0 Ops/sec |
Sort With Reduce | 141.4 Ops/sec |
var array = [];
array.length = 10000;
array.fill(undefined);
array = array.map(() => Math.floor(Math.random() * array.length));
const set = new Set(array);
const maxSetValue = array.reduce(Math.max);
function findSet() {
for (let i = 0; i < maxSetValue; i++)
if (!set.has(i)) return i;
return -1;
}
findSet();
const sortedArray = array.slice().sort((a, b) => a - b);
const maxSortValue = sortedArray[array.length - 1];
function findSort() {
for (let i = 0; i < maxSortValue; i++)
if (!sortedArray.includes(i)) return i;
return -1;
}
findSort();
const sortedReduceArray = array.slice().sort((a, b) => a - b);
function findReduce() {
return sortedReduceArray.reduce((acc, current) => (Math.abs(current - acc) > 1 ? Math.min : Math.max)(current, acc), 0) + 1;
}
findReduce();