diff options
author | 2022-03-31 00:33:29 +0200 | |
---|---|---|
committer | 2022-03-31 00:33:29 +0200 | |
commit | 64c92a661ccf1fb6a6482c5504db97dbcb003977 (patch) | |
tree | d6c11f07c766ffe72c2e54e802d4f86c33517c2a /src/utils | |
download | it-tools-64c92a661ccf1fb6a6482c5504db97dbcb003977.tar.gz it-tools-64c92a661ccf1fb6a6482c5504db97dbcb003977.tar.zst it-tools-64c92a661ccf1fb6a6482c5504db97dbcb003977.zip |
chore: first commit
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/random.ts | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/src/utils/random.ts b/src/utils/random.ts new file mode 100644 index 0000000..6df941d --- /dev/null +++ b/src/utils/random.ts @@ -0,0 +1,21 @@ +const random = () => Math.random(); + +const randFromArray = (array: unknown[]) => array[Math.floor(random() * array.length)]; + +const randIntFromInterval = (min: number, max: number) => Math.floor(random() * (max - min) + min); + +// Durstenfeld shuffle +const shuffleArrayMutate = <T>(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>(array: T[]): T[] => shuffleArrayMutate([...array]); + +const shuffleString = (str: string, delimiter = ''): string => shuffleArrayMutate(str.split(delimiter)).join(delimiter); + +export { randFromArray, randIntFromInterval, random, shuffleArray, shuffleArrayMutate, shuffleString }; |