@cp949/utilx
v1.1.0
Published
Small practical utilities: DisposableScope, URLCreateRegistry, BoundedBuffer, genId. No rxjs dependency.
Downloads
157
Readme
@cp949/utilx
앱 코드에서 자주 마주치는 자잘하지만 성가신 유틸을 모아둔 zero-dependency 패키지입니다.
브라우저 리소스 정리용 DisposableScope, URLCreateRegistry와 함께 고정 길이 로그 버퍼용 BoundedBuffer, genId를 제공합니다.
설치
pnpm add @cp949/utilx제공 API
DisposableScopedelayDisposableAbortControllerDisposableTimeoutlistensetDisposableTimeoutURLCreateRegistryBoundedBuffergenIdgenUid
DisposableScope
import { DisposableScope } from "@cp949/utilx";
const scope = new DisposableScope();
scope.listen(window, "resize", () => {});
scope.setTimeout(() => {}, 1000);
scope.dispose();dispose()는 idempotent하며 등록된 cleanup을 역순(LIFO)으로 실행합니다.- 이미 dispose된 scope에
use()하면 리소스를 즉시 정리한 뒤 에러를 던집니다. toCleanup()정규화 순서는dispose -> close -> unsubscribe -> abort -> terminate -> destroy -> shutdown입니다.adopt()대상은dispose()가 idempotent여야 하며onDispose를 최대 한 번 호출해야 합니다.
URLCreateRegistry
import { URLCreateRegistry } from "@cp949/utilx";
const registry = new URLCreateRegistry();
const blob = new Blob(["hello"], { type: "text/plain" });
const url = registry.acquire(blob);
registry.release(blob);
registry.revoke(url);URLCreateRegistry는 FinalizationRegistry를 대체하지 않습니다.
가비지 컬렉션 시점에 자동 정리를 기대하면 안 되며, release(), revoke(), revokeAll()로 직접 수명을 관리해야 합니다.
BoundedBuffer
import { BoundedBuffer } from "@cp949/utilx";
const list = new BoundedBuffer<number>(3);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.toArray(); // [2, 3, 4]push()는 새 항목을 뒤에 추가하고, max size를 넘기면 가장 오래된 항목부터 제거합니다.shift()는 가장 오래된 항목을 꺼냅니다.peekOldest(),peekNewest()로 양 끝 값을 확인할 수 있습니다.clone()은 같은 내용을 가진 독립 버퍼를 만듭니다.
genId, genUid
import { genId, genUid } from "@cp949/utilx";
const taken = new Set(["item-abcd1234"]);
const id = genId("item-", (value) => taken.has(value));
const uid = genUid();genId(prefix, existing)는 prefix 기반 랜덤 ID를 만들고, 충돌 시 길이를 늘려 다시 시도합니다.genUid()는 더 긴 랜덤 문자열을 생성합니다.
