randomInt

지정된 범위 내의 정수 난수를 생성하는 함수입니다.

Signatures

function randomInt(max: number): number;
function randomInt(min: number, max: number): number;

Parameters

이름타입설명필수 여부
minnumber최소값 (두 번째 인자로 사용 시 최대값)
maxnumber최대값-

Returns

number - min(포함)과 max(미포함) 사이의 정수 난수

Errors

다음과 같은 경우에 에러가 발생합니다:

  • 최소값이 최대값보다 큰 경우
  • 최소값과 최대값이 같은 경우

사용 예시

import { randomInt } from '@teamsparta/utils';
 
// 단일 인자 사용 (0부터 시작)
randomInt(5); // 0, 1, 2, 3, 4 중 하나
randomInt(2); // 0, 1 중 하나
 
// 범위 지정
randomInt(1, 4); // 1, 2, 3 중 하나
randomInt(0, 2); // 0, 1 중 하나
 
// 음수 범위
randomInt(-5, -2); // -5, -4, -3 중 하나
 
// 음수와 양수가 혼합된 범위
randomInt(-2, 2); // -2, -1, 0, 1 중 하나
 
// 인접한 정수
randomInt(1, 2); // 항상 1을 반환
 
// 큰 범위
randomInt(-1000000, 1000000); // -1000000 이상 1000000 미만의 정수
 
// 에러 발생 케이스
randomInt(5, 0); // Error: Invalid input: The maximum value must be greater than the minimum value.
randomInt(5, 5); // Error: Invalid input: The maximum value must be greater than the minimum value.