Last active
January 22, 2025 14:57
-
-
Save anechunaev/1819c9b6283c20a18520539456fbdac1 to your computer and use it in GitHub Desktop.
Pseudo-random number generator for TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let storedSeed: number = 1337; | |
// MurmurHash3 | |
export function seed(str: string): void { | |
for(let i = 0, h = 1779033703 ^ str.length; i < str.length; i++) { | |
h = Math.imul(h ^ str.charCodeAt(i), 3432918353), | |
h = h << 13 | h >>> 19; | |
if (i === str.length - 1) { | |
storedSeed = h; | |
} | |
} | |
} | |
// SplitMix32 | |
export function rand(): number { | |
storedSeed |= 0; storedSeed = storedSeed + 0x9e3779b9 | 0; | |
let t = storedSeed ^ storedSeed >>> 16; t = Math.imul(t, 0x21f0aaad); | |
t = t ^ t >>> 15; t = Math.imul(t, 0x735a2d97); | |
return ((t = t ^ t >>> 15) >>> 0) / 4294967296; | |
} | |
// Pseudo UUID | |
export function guid(): string { | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { | |
const r = rand() * 16 | 0; | |
const v = c === 'x' ? r : (r & 0x3 | 0x8); | |
return v.toString(16); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment