Skip to content

compact

김태헌 edited this page Sep 26, 2024 · 3 revisions

예시 1: 배열에서 falsy 값 제거

import { compact } from 'mori-ts';

const arr = [1, 2, 3, 0, null, undefined, false, 5];

const result = [...compact(arr)];

console.log(result); // 출력: [1, 2, 3, 5]

예시 2: 비동기 iterable에서 falsy 값 제거

import { compact, toArray } from 'mori-ts';

const asyncIterable = (async function* () {
  yield 1;
  yield null;
  yield 2;
  yield undefined;
  yield 3;
  yield false;
})();

const result = await toArray(compact(asyncIterable));

console.log(result); // 출력: [1, 2, 3]

예시 3: 파이프라인과 함께 사용

import { pipe, range, map, compact, toArray } from 'mori-ts';

const res = pipe(
  range(1, 10),
  map(n => (n % 2 === 0 ? 0 : n)),
  compact,
  toArray,
);

console.log(res); // 출력: [1, 3, 5, 7, 9]

테스트 코드 링크

https://github.com/gangnamssal/mori-ts/blob/main/src/test/compact.spec.ts

Clone this wiki locally