Skip to content

Commit

Permalink
perf: random[Key](): use Durstenfeld shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
Renegade334 committed Nov 4, 2024
1 parent b93437c commit a0722aa
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions packages/collection/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,12 @@ export class Collection<Key, Value> extends Map<Key, Value> {
if (!amount) return [];

const values = [...this.values()];
// eslint-disable-next-line unicorn/no-new-array
const results: Value[] = new Array(amount);
for (let index = 0; index < amount; index++) {
results[index] = values.splice(Math.floor(Math.random() * values.length), 1)[0]!;
for (let sourceIndex = 0; sourceIndex < amount; sourceIndex++) {
const targetIndex = sourceIndex + Math.floor(Math.random() * (values.length - sourceIndex));
[values[sourceIndex], values[targetIndex]] = [values[targetIndex]!, values[sourceIndex]!];
}

return results;
return values.slice(0, amount);
}

/**
Expand All @@ -240,13 +239,12 @@ export class Collection<Key, Value> extends Map<Key, Value> {
if (!amount) return [];

const keys = [...this.keys()];
// eslint-disable-next-line unicorn/no-new-array
const results: Key[] = new Array(amount);
for (let index = 0; index < amount; index++) {
results[index] = keys.splice(Math.floor(Math.random() * keys.length), 1)[0]!;
for (let sourceIndex = 0; sourceIndex < amount; sourceIndex++) {
const targetIndex = sourceIndex + Math.floor(Math.random() * (keys.length - sourceIndex));
[keys[sourceIndex], keys[targetIndex]] = [keys[targetIndex]!, keys[sourceIndex]!];
}

return results;
return keys.slice(0, amount);
}

/**
Expand Down

0 comments on commit a0722aa

Please sign in to comment.