npm.io
1.1.0 • Published yesterday

@cp949/js-util

Licence
MIT
Version
1.1.0
Deps
0
Size
377 kB
Vulns
0
Weekly
0

@cp949/js-util

npm version License: MIT

유지보수 중단

이 라이브러리는 더 이상 버그 수정이나 기능 추가를 하지 않습니다. 보안 취약점 관련 업데이트만 유지합니다. 새로 시작하는 프로젝트에서는 lodash-eses-toolkit을 사용하세요.

브라우저에서 사용하는 TypeScript 유틸리티 모음입니다. 19개 서브모듈을 개별 진입점으로 제공하며, 각 모듈은 독립적으로 import 합니다.

설치

npm install @cp949/js-util
pnpm add @cp949/js-util
yarn add @cp949/js-util

지원 환경

이 라이브러리는 브라우저 전용입니다. btoa, TextEncoder, document 같은 브라우저 API를 사용하므로 Node.js 런타임에서는 동작을 보장하지 않습니다.

항목
브라우저 Chrome 75+, Edge 79+, Firefox 68+, Safari 14.1+
모듈 형식 ESM, CJS
타입 선언 포함 (.d.ts, .d.cts)
소스맵 포함

빌드 타겟은 ['chrome75', 'safari14.1', 'firefox68', 'edge79']입니다. ?., ?? 같은 문법은 빌드 시점에 다운레벨되며, 런타임 폴리필은 포함하지 않습니다.

import

루트 진입점 @cp949/js-util은 export를 제공하지 않습니다. 서브패스로 import 하세요.

import { chunks, groupBy } from '@cp949/js-util/array';
import { camelCase, isBlank } from '@cp949/js-util/string';
import { clamp } from '@cp949/js-util/math';

서브패스별로 진입점이 분리되어 있어, import 하지 않은 모듈은 번들에 포함되지 않습니다.

모듈

서브패스 export 대표 함수
@cp949/js-util/array 50 append/$append, chunks, groupBy, uniqBy, zipWith
@cp949/js-util/string 57 camelCase, isBlank, truncMiddle, formatByteCount, chosung
@cp949/js-util/math 39 clamp, degToRad, cycle, atLeast, atMost
@cp949/js-util/easing 31 backIn, bounceOut, circInOut 등 이징 함수
@cp949/js-util/misc 30 deepEq, shallowEq, sleepAsync, isNullish, pathUtil
@cp949/js-util/random 27 randomInt, randomBoolean, randomUint8Array, suid
@cp949/js-util/color 17 hex2rgb, rgb2hsl, blend, darken
@cp949/js-util/uint8-array 17 stringToBase64, base64ToString, uint8ArrayToHex, concatUint8Arrays
@cp949/js-util/dataurl 11 extractMimeType, getDataURLSize, convertBlobToDataURL
@cp949/js-util/base64 6 encode, decode, uint8ArrayToBase64, base64ToUint8Array
@cp949/js-util/date 6 formatByEpochMillis, formatByEpochSeconds, formatter, parser
@cp949/js-util/http 5 joinUrl, objectToQueryString, queryParams
@cp949/js-util/usermedia 5 hasGetUserMedia, closeUserMedia, fixUserMedia
@cp949/js-util/dom 4 qs, qsa, createElement, addGlobalEventListener
@cp949/js-util/browser 3 isTouchDevice, isWebSerialSupport, isWebBluetoothSupport
@cp949/js-util/web 3 downloadBlob, downloadLink, downloadText
@cp949/js-util/file 2 fileExtension, fileNamePart
@cp949/js-util/eventemitter 1 EventEmitter
@cp949/js-util/fn 1 debounce

사용 예시

아래 출력값은 실제 실행 결과입니다.

배열
import { append, $append, chunks, groupBy, uniqBy } from '@cp949/js-util/array';

chunks([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]

uniqBy([{ id: 1 }, { id: 1 }, { id: 2 }], 'id');
// [{ id: 1 }, { id: 2 }]

groupBy([{ t: 'a', v: 1 }, { t: 'b', v: 2 }, { t: 'a', v: 3 }], 't');
// { a: [{ t: 'a', v: 1 }, { t: 'a', v: 3 }], b: [{ t: 'b', v: 2 }] }
문자열
import { camelCase, isBlank, truncMiddle, formatByteCount } from '@cp949/js-util/string';

camelCase('hello', 'world');            // 'helloWorld'
isBlank('   ');                         // true
truncMiddle('abcdefghijklmnop', { length: 9 }); // 'abc...nop'
formatByteCount(1536);                  // '1.5 KB'

camelCase는 전달한 조각들을 이어 붙입니다. 하나의 문자열 안에 있는 _-를 변환하지는 않습니다.

base64와 Uint8Array
import { stringToBase64, base64ToString, uint8ArrayToHex, stringToUint8Array }
  from '@cp949/js-util/uint8-array';

stringToBase64('안녕 js-util');        // '7JWI64WVIGpzLXV0aWw='
base64ToString('7JWI64WVIGpzLXV0aWw='); // '안녕 js-util'
uint8ArrayToHex(stringToUint8Array('js')); // '6a73'

문자열만 다룰 때는 base64 모듈이 더 짧습니다.

import { encode, decode } from '@cp949/js-util/base64';

encode('안녕 js-util');          // '7JWI64WVIGpzLXV0aWw='
decode('7JWI64WVIGpzLXV0aWw='); // '안녕 js-util'

두 모듈 모두 TextEncoder/TextDecoder를 거치므로 비ASCII 문자열도 그대로 왕복합니다. base64는 문자열을, uint8-array는 바이트 배열을 중심으로 다룹니다.

URL과 숫자
import { joinUrl, objectToQueryString } from '@cp949/js-util/http';
import { clamp } from '@cp949/js-util/math';
import { fileExtension } from '@cp949/js-util/file';

joinUrl('https://api.test', '/v1/', 'users'); // 'https://api.test/v1/users'
objectToQueryString({ page: 2 });             // '?page=2'
clamp(15, 0, 10);                             // 10
fileExtension('report.final.PDF');            // 'PDF'
fileExtension('report.PDF', true, true);      // '.pdf'

objectToQueryString은 값을 URL 인코딩하지 않습니다. 인코딩이 필요한 값은 호출 전에 encodeURIComponent로 처리하세요. falsy 값(0, false, '', null, undefined)을 가진 항목은 결과에서 빠집니다.

mutable과 immutable

array 모듈은 같은 동작을 두 가지 형태로 제공합니다. $ 접두사가 붙은 함수는 원본을 두고 새 배열을 반환합니다.

import { append, $append } from '@cp949/js-util/array';

const a = [1, 2, 3];
append(a, [4, 5]);   // a 자체가 [1, 2, 3, 4, 5]로 바뀐다

const b = [1, 2, 3];
const c = $append(b, [4, 5]);
// b === [1, 2, 3]  (유지)
// c === [1, 2, 3, 4, 5]

$ 쌍이 있는 함수: append, prepend, insertAt, remove, removeAt, replace, replaceAt, move, swap, swapValue, shuffle, truncate, uniq, uniqBy, shiftRotateLeft, shiftRotateRight.

date 모듈과 dayjs

date 모듈은 dayjs를 optional peer dependency로 사용합니다. 이 모듈을 쓸 때만 설치하세요.

npm install dayjs
import { formatByEpochMillis } from '@cp949/js-util/date';

formatByEpochMillis(0, 'YYYY-MM-DD');
// ['1970-01-01', Date(1970-01-01T00:00:00.000Z)]

포맷 결과와 Date 객체를 튜플로 반환합니다. 입력이 유효하지 않으면 실행 시점에 [null, null]을 반환합니다. 타입 선언은 [string | undefined, Date | undefined]로 되어 있어 런타임 값과 다릅니다.

TypeScript

각 서브패스는 ESM(.d.ts)과 CJS(.d.cts) 타입 선언을 따로 제공합니다. tsconfig.jsonmoduleResolutionnode16, nodenext, bundler 중 하나여야 서브패스 타입이 해석됩니다.

{
  "compilerOptions": {
    "moduleResolution": "bundler"
  }
}

링크

라이선스

MIT

Keywords