Maemaemae

整数型でランダムの値を取得する関数

最小値と最大値を指定したら、その間の値をランダムで返します。

コード

/**
 * ランダム整数取得関数
 * @param min
 * @param max
 * @returns
 */
export function getRandomInt({
  min,
  max,
}: {
  min: number;
  max: number;
}): number {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Math.ceil()

引数として与えられた数以上の最小の整数を返します。

number型は整数以外も許容するので整数に変換しています。

Math.ceil(0.95); // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(-0.95); // -0
Math.ceil(-4); // -4
Math.ceil(-7.004); // -7

Math.floor()

与えられた数値以下の最大の整数を返します。

仕様によってはMath.ceil()にします。

Math.floor(3.34); // 3
Math.floor(5.67); // 5
Math.floor(-3.34); // -4
Math.floor(-5.67); // -6
typescript