Test name | Executions per second |
---|---|
Set With For Loop | 4812.8 Ops/sec |
Sort With For Loop | 642.0 Ops/sec |
Sort With Reduce | 329.5 Ops/sec |
var array = [];
array.length = 10000;
array.fill(undefined);
array = array.map(() => Math.floor(Math.random() * array.length));
const set = new Set(array);
function findSet() {
for (let i = 0; i < array.length; i++)
if (!set.has(i)) return i;
return -1;
}
findSet();
const sortedArray = array.slice().sort((a, b) => a - b);
function findSort() {
for (let i = 0; i < array.length; 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();