-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.ts
54 lines (40 loc) · 1.42 KB
/
random.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Chooses a random item from the array and returns it
*/
export function chooseRandArrItem<T>(arr: T[]): T {
if (!arr.length) throw new Error(`Cannot choose a random item from an empty array!`)
return arr[randomNumber(0, arr.length - 1)]
}
/**
* Returns a random number between `min` and `max` (both included)
*/
export function randomNumber(min: number, max: number): number {
if (max < min) throw new Error(`Cannot choose a random number: 'max' is less than 'min'`)
if (max === min) return max
return Math.floor(Math.random() * (max - min + 1)) + min
}
export function chooseArrItemFromString<T>(str: string, arr: T[]): T {
if (!arr.length) throw new Error(`Array is empty. No items to choose from`)
if (arr.length === 1) return arr[0]
const num = getHash(str, 0, arr.length - 1)
return arr[num]
}
const chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('')
export function getHash(str: string, min: number, max: number): number {
min = Math.round(min)
max = Math.round(max)
if (min >= max) throw new Error(`After rounding to the nearest whole number, max was not greater than min`)
let num = min
btoa(str)
.split('')
.forEach((char) => {
if (char === '=') return
char = char.toLowerCase()
const index = chars.indexOf(char)
if (index === -1) throw new Error(`Unrecognized char: ${char}`)
num = num + index
if (num > max) num = num - max
})
while (num > max) num = num - max
return num
}