refactor: improved shuffle function (now using Durstenfeld shuffle)

This commit is contained in:
Corentin Thomasset 2021-06-12 22:22:23 +02:00
parent 436d960603
commit 1ebfe83d20
No known key found for this signature in database
GPG key ID: DBD997E935996158
4 changed files with 23 additions and 8 deletions

View file

@ -6,8 +6,25 @@ const randFromArray = (array: any[]) => array[Math.floor(random() * array.length
const randIntFromInterval = (min: number, max: number) => Math.floor(random() * (max - min) + min)
// Durstenfeld shuffle
const shuffleArrayMutate = <T extends unknown>(array: T[]): T[] => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array
}
const shuffleArray = <T extends unknown>(array: T[]): T[] => shuffleArrayMutate([...array])
const shuffleString = (str: string, delimiter: string = ''): string => shuffleArrayMutate(str.split(delimiter)).join(delimiter)
export {
randFromArray,
randIntFromInterval,
random
random,
shuffleArray,
shuffleArrayMutate,
shuffleString
}

View file

@ -1,5 +1,3 @@
const capitalise = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
const shuffle = (s: string) => s.split('').sort(() => 0.5 - Math.random()).join('')
export {capitalise, shuffle}
export {capitalise}