Range: The Math.random() function in TypeScript generates a pseudo-random floating-point number in the range from 0 (inclusive) to 1 (exclusive). This means it can return 0 but will never reach 1.
const randomNumber = Math.random(); // Generates a random number between 0 (inclusive) and 1 (exclusive)
Seedless: Unlike some other programming languages, TypeScript's Math.random doesn't allow you to set a seed value. The seed is a starting point for the random number generator, and without it, the sequence of random numbers is different every time the program runs.
Pseudo-Random: The numbers generated by Math.random are not truly random but rather pseudo-random. They are determined by an algorithm, and the sequence of numbers appears random, but it's deterministic if you know the initial conditions. Custom Range: You can create a random number within a custom range by combining Math.random with some arithmetic operations. For example, to get a random integer between two values (inclusive), you can use the following formula:
const min = 1; const max = 10; const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
Math.random
to generate a random boolean value. For example:
const randomBoolean = Math.random() < 0.5; // 50% chance of being true or false
Random Array Element: You can use Math.random to pick a random element from an array:
const myArray = [1, 2, 3, 4, 5]; const randomElement = myArray[Math.floor(Math.random() * myArray.length)];
UUID Generation:Math.random
is often used as part of algorithms to generate unique identifiers (UUIDs) in TypeScript.
const uuid = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); }; const randomUUID = uuid();
0 Comments