f7
f7 is a spreadsheet formula execution library
git clone https://git.vogt.world/f7.git
Log | Files | README.md | LICENSE.md
← All files
name: src/main/js/common/utils/Random.ts
-rw-r--r--
2263
 1const ALPHA_NUMERIC_ALL_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 2const ALPHA_UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 3
 4/**
 5 * Return a random 16 character string.
 6 * https://gist.github.com/jcxplorer/823878
 7 */
 8export function randomID() {
 9  return randomString(16);
10}
11
12/**
13 * Generate a random UUID.
14 * https://gist.github.com/jcxplorer/823878
15 */
16export function randomUUID() {
17  let uuid = "",
18    i,
19    random;
20  for (i = 0; i < 32; i++) {
21    random = (Math.random() * 16) | 0;
22    if (i == 8 || i == 12 || i == 16 || i == 20) {
23      uuid += "-";
24    }
25    uuid += (i == 12 ? 4 : i == 16 ? (random & 3) | 8 : random).toString(16);
26  }
27  return uuid;
28}
29
30/**
31 * Generate a random string of N length.
32 * https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
33 * @param n - length of string returned
34 */
35export function randomString(n: number) {
36  return randomFrom(n, ALPHA_NUMERIC_ALL_CASE);
37}
38
39/**
40 * Generate a random string of length N.
41 * @param n
42 */
43export function randomAlphaUppercase(n: number) {
44  return randomFrom(n, ALPHA_UPPER_CASE);
45}
46
47function randomFrom(n: number, characters: string) {
48  let text = "";
49
50  for (let i = 0; i < n; i++)
51    text += characters.charAt(Math.floor(Math.random() * characters.length));
52
53  return text;
54}
55
56/**
57 * Generate a hashcode for a given input string.
58 * https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
59 *
60 * @param input - the input to hash.
61 * @param seed - seed to use.
62 */
63export function hashCode(input: string, seed = 0x811c9dc5) {
64  let i,
65    l,
66    hval = seed;
67  for (i = 0, l = input.length; i < l; i++) {
68    hval ^= input.charCodeAt(i);
69    hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
70  }
71  // Convert to 8 digit hex string
72  return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
73}
74
75/**
76 * Generate a hashcode for a given object.
77 *
78 * @param input - the input to hash.
79 * @param seed - seed to use.
80 */
81export function objectHashCode(input: any, seed?: number) {
82  return hashCode(JSON.stringify(input), seed);
83}
84
85/**
86 * Random int between 0 and 2,147,483,647.
87 */
88export function randomInt() {
89  return Math.floor(Math.random() * 2147483647);
90}