how to use the random function from the lodash library in typescript

To use the random function from the lodash library in a TypeScript project, you must first install the library via npm:

index.ts
npm install --save lodash
26 chars
2 lines

Once installed, you can import the random function into your TypeScript code and use it as follows:

index.ts
import { random } from 'lodash';

const randomNumber = random(0, 100);  // Generates a random number between 0 and 100 (inclusive)
console.log(randomNumber);  // Prints a random number between 0 and 100 (inclusive)
215 chars
5 lines

The random function can also generate random numbers within a custom range, using a floating point precision specification, and with the option to generate unique numbers through shuffling:

index.ts
import { random } from 'lodash';

const randomInt = random(1, 10);  // Generates a random integer between 1 and 10 (inclusive)
const randomFloat = random(1.5, 2.5, true);  // Generates a random float between 1.5 and 2.5 (inclusive), with one decimal point of precision
const randomUnique = random(1, 5, true, [3, 5]);  // Generates a random integer between 1 and 5 (inclusive) that is not already in the provided array; e.g., can return 1, 2, 4, or any other integer not equal to 3 or 5
487 chars
6 lines

Note that the random function from lodash follows the same rules as the Math.random() function in JavaScript, generating uniformly-distributed pseudorandom numbers between 0 and 1.

gistlibby LogSnag