mirror of
https://github.com/jeffvli/feishin.git
synced 2026-07-05 10:09:58 +02:00
perf: use crypto.getRandomValues() for higher-quality shuffle in music player (#2181)
* fix: use crypto-safe randomness in shuffle helpers
This commit is contained in:
@@ -1,22 +1,22 @@
|
|||||||
export function shuffle<T>(array: T[]): T[] {
|
export function shuffle<T>(array: T[]): T[] {
|
||||||
// Create a copy of the array to avoid mutating the original
|
return shuffleInPlace(array.slice());
|
||||||
const shuffled = [...array];
|
|
||||||
|
|
||||||
// Loop through the array from the last element to the first
|
|
||||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
|
||||||
// Generate a random index from 0 to i
|
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
|
||||||
// Swap elements at positions i and j
|
|
||||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
|
||||||
}
|
|
||||||
|
|
||||||
return shuffled;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shuffleInPlace<T>(array: T[]): T[] {
|
export function shuffleInPlace<T>(array: T[]): T[] {
|
||||||
for (let i = array.length - 1; i > 0; i--) {
|
for (let i = array.length - 1; i > 0; i--) {
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
const j = Math.floor(cryptoRandom() * (i + 1));
|
||||||
[array[i], array[j]] = [array[j], array[i]];
|
[array[i], array[j]] = [array[j], array[i]];
|
||||||
}
|
}
|
||||||
return array;
|
return array;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const randomBuffer = new Uint32Array(1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a cryptographically secure random float in [0, 1),
|
||||||
|
* matching the contract of Math.random().
|
||||||
|
*/
|
||||||
|
function cryptoRandom(): number {
|
||||||
|
crypto.getRandomValues(randomBuffer);
|
||||||
|
return randomBuffer[0] / 0x100000000;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user