function to generate random number with a lowerbound and upperbound parameter in typescript

To generate a random number in TypeScript within a specified range, we can write the following function:

index.ts
function generateRandomNumber(lowerBound: number, upperBound: number): number {
  return Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
}
163 chars
4 lines

In this function, we take in two parameters, lowerBound and upperBound, which determine the range within which we want to generate our random number. We use the Math.random() function, which returns a random number between 0 and 1, and multiply it by the difference between upperBound and lowerBound to get a number in the range of 0 to upperBound - lowerBound.

We then add lowerBound to shift the range to start at lowerBound, and wrap the whole thing in Math.floor() to get an integer.

Note that we add 1 to the difference between upperBound and lowerBound so that the upper bound is inclusive, meaning that if lowerBound and upperBound are the same, the function will always return that value.

gistlibby LogSnag