Skip to content

Commit

Permalink
Update comments and add Random.float() and Random.integer()
Browse files Browse the repository at this point in the history
  • Loading branch information
FinlayDaG33k committed Jan 17, 2024
1 parent 01fd913 commit 23bfecd
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions security/random.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export class Random {
/**
* Generate random bytes
* Generate random bytes.
* These bytes are generated using the Web Crypto API, this cryptographically secure.
*
* @param length Amount of bytes to be generated
* @returns Uint8Array
Expand All @@ -12,7 +13,8 @@ export class Random {
}

/**
* Generate a random string
* Generate a random string.
* These strings are generated using the Web Crypto API, this cryptographically secure.
*
* @param length Length of the string to be generated
* @returns Promise<string>
Expand All @@ -21,4 +23,45 @@ export class Random {
const buf = await Random.bytes(length / 2);
return Array.from(buf, (dec: number) => dec.toString(16).padStart(2, "0")).join('');
}

/**
* Inclusively generate a random integer between min and max.
* If you want to use decimals, please use Random.float() instead.
*
* By default, these integers are **NOT** cryptographically secure (for performance reasons).
* Set the "secure" argument to "true" if you are using this for cryptographic purposes!
*
* @param min Minimum allowable integer
* @param max Maximum allowable integer
* @param secure Using this for cryptographic purposes?
*/
public static integer(min = 0, max = 1, secure = false): number {
// Strip decimals
min = Math.ceil(min);
max = Math.floor(max);

// Generate a number using Random.float and floor that
return Math.floor(Random.float(min, max, secure));
}

/**
* Inclusively generate a random float between min and max.
* If you do not want to use decimals, please use Random.integer() instead.
*
* By default, these floats are **NOT** cryptographically secure (for performance reasons).
* Set the "secure" argument to "true" if you are using this for cryptographic purposes!
*
* @param min Minimum allowable float
* @param max Maximum allowable float
* @param secure Using this for cryptographic purposes?
*/
public static float(min = 0, max = 1, secure = false): number {
// Generate our randomness
const random = secure
? crypto.getRandomValues(new Uint32Array(1))[0] / Math.pow(2, 32)
: Math.random();

// Limit and return
return random * (max - min + 1) + min;
}
}

0 comments on commit 23bfecd

Please sign in to comment.