Skip to content

Utils - Math

@teamsparta/utils에서 제공하는 수학 관련 유틸리티 함수입니다.


clamp

주어진 값을 최솟값과 최댓값 사이로 제한합니다.

API

typescript
// 오버로드 1: 최댓값만 지정 (0 ~ max)
function clamp(value: number, max: number): number;

// 오버로드 2: 최솟값과 최댓값 지정 (min ~ max)
function clamp(value: number, min: number, max: number): number;

사용 예시

typescript
import { clamp } from '@teamsparta/utils';

clamp(3, 5);       // 3 (5 이하이므로 그대로)
clamp(10, 6);      // 6 (6으로 제한)
clamp(7, 0, 10);   // 7 (범위 내)
clamp(-5, 0, 10);  // 0 (최솟값으로 제한)
clamp(15, 0, 10);  // 10 (최댓값으로 제한)

random

지정된 범위 내의 랜덤 실수를 반환합니다.

API

typescript
// 오버로드 1: 0 ~ max
function random(max: number): number;

// 오버로드 2: min ~ max
function random(min: number, max: number): number;

사용 예시

typescript
import { random } from '@teamsparta/utils';

random(10);     // 0 ~ 10 사이 랜덤 실수
random(5, 10);  // 5 ~ 10 사이 랜덤 실수

randomInt

지정된 범위 내의 랜덤 정수를 반환합니다.

API

typescript
// 오버로드 1: 0 ~ max (소수점 버림)
function randomInt(max: number): number;

// 오버로드 2: min ~ max (소수점 버림)
function randomInt(min: number, max: number): number;

사용 예시

typescript
import { randomInt } from '@teamsparta/utils';

randomInt(10);     // 0 ~ 9 사이 랜덤 정수
randomInt(5, 10);  // 5 ~ 9 사이 랜덤 정수

sumBy

배열의 각 요소에서 특정 값을 추출하여 합산합니다.

API

typescript
function sumBy<T>(items: readonly T[], getValue: (item: T) => number): number;

사용 예시

typescript
import { sumBy } from '@teamsparta/utils';

const products = [
  { name: 'A', price: 1000 },
  { name: 'B', price: 2000 },
  { name: 'C', price: 3000 },
];

sumBy(products, (p) => p.price); // 6000