@toktokhan-dev/universal
Version:
A universal library built by TOKTOKHAN.DEV
1,856 lines (1,784 loc) • 55.2 kB
TypeScript
import { CurriedFunction2 } from 'lodash';
/**
* 배열을 Map으로 변환합니다. 각 요소는 지정된 키 선택기 함수를 통해 매핑됩니다.
*
* @curried
* @category Utils/Array
*
* @typeParam T - 배열 요소의 타입
* @typeParam K - Map의 키 타입
*
* @param keySelector - 배열 요소를 Map의 키로 변환하는 함수
* @param arr - 변환할 배열
*
* @returns 배열의 각 요소를 Map으로 매핑한 결과
*
* @example
* ```ts
* const arr = [
* { id: 1, name: 'Alice' },
* { id: 2, name: 'Bob' },
* { id: 3, name: 'Charlie' },
* ];
*
* const map = arrayToMap((item) => item.id , arr);
* // or
* const map = arrayToMap((item) => item.id)(arr);
* // or
* const mapById = arrayToMap((item) => item.id);
* const map = mapById(arr);
*
* console.log(map)
* // Map {
* // 1 => { id: 1, name: 'Alice' },
* // 2 => { id: 2, name: 'Bob' },
* // 3 => { id: 3, name: 'Charlie' },
* // }
*```
*/
declare const arrayToMap: {
<T, K>(keySelector: (data: T) => K, arr: T[]): Map<K, T>;
<T, K>(keySelector: (data: T) => K): (arr: T[]) => Map<K, T>;
};
/**
* 배열을 Record로 변환합니다. 각 요소는 지정된 키 선택기 함수를 통해 매핑됩니다.
*
* @curried
* @category Utils/Array
*
* @typeParam T - 배열 요소의 타입
* @typeParam K - Record의 키 타입 (string, number, symbol)
*
* @param keySelector - 배열 요소를 Record의 키로 변환하는 함수
* @param arr - 변환할 배열
*
* @returns 배열의 각 요소를 Record으로 매핑한 결과
*
* @example
* ```ts
* const arr = [
* { id: 1, name: 'Alice' },
* { id: 2, name: 'Bob' },
* { id: 3, name: 'Charlie' },
* ];
*
* const record = arrayToRecord((item) => item.id , arr);
* // or
* const record = arrayToRecord((item) => item.id)(arr);
* // or
* const recordById = arrayToRecord((item) => item.id);
* const record = recordById(arr);
*
* console.log(record)
* // {
* // 1: { id: 1, name: 'Alice' },
* // 2: { id: 2, name: 'Bob' },
* // 3: { id: 3, name: 'Charlie' },
* // }
*```
*/
declare const arrayToRecord: {
<T, K extends string | number | symbol>(keySelector: (data: T) => K, arr: T[]): Record<K, T>;
<T, K extends string | number | symbol>(keySelector: (data: T) => K): (arr: T[]) => Record<K, T>;
};
/**
* @category Utils/Array
*
* 배열을 특정 갯수로 나누어주는 함수입니다.
*
* @param limit - 배열을 나눌 갯수입니다.
* @param arr - 나눌 배열입니다.
*
* @returns 나누어진 배열을 반환합니다.
*
* @example
*
* ```ts
* const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
* const result = paginate(3, arr)
*
* console.log(result)
*
* // [
* // [1, 2, 3],
* // [4, 5, 6],
* // [7, 8, 9],
* // ]
* ```
*/
declare const paginate: {
<T>(limit: number, arr: T[]): T[][];
<T>(limit: number): (arr: T[]) => T[][];
};
/**
* 재귀하는 타입을 가지는 객체를 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입입니다.
* @returns 재귀하는 타입을 가지는 객체의 타입
*
* @example
*
* ```typescirpt
*
* const Object: RecursiveObj<{ src: string; alt: string }> = {
* a: {
* alt: 'a.alt',
* src: 'a.src',
* },
* b: {
* c: {
* alt: 'c.alt',
* src: 'c.src',
* },
* d: {
* alt: 'd.alt',
* src: 'd.src',
* },
* },
* }
* ```
*/
type RecursiveObj<T> = {
[x in string]: T | RecursiveObj<T>;
};
/**
* `flatObject` 함수의 매개변수 타입입니다.
*
* @typeParam T - 재귀적으로 중첩된 객체의 타입
* @typeParam V - 중첩된 객체의 값의 타입
*
* @property separator - 객체의 키를 연결할 때 사용할 구분자
* @property filter - 객체의 값을 필터링하는 함수. 이 함수가 `true`를 반환하면 해당 값이 결과에 포함됩니다.
*/
type FlatObjectParams<T extends RecursiveObj<any>, V = T extends RecursiveObj<infer U> ? U : never> = {
isValueType?: (value: T | V) => boolean;
formatKey?: (parentKey: string | null, currentKey: string) => string;
formatValue?: (data: {
key: string;
value: V;
}) => any;
};
/**
* 재귀적으로 중첩된 객체를 평탄화하는 함수입니다.
*
* @category Utils/Object
*
* @typeParam T - 재귀적으로 중첩된 객체의 타입
* @typeParam V - 중첩된 객체의 값의 타입
*
* @param params - 평탄화 작업에 필요한 매개변수
* @param obj - 평탄화할 객체
* @returns 평탄화된 객체. 키는 문자열이고 값은 V 타입입니다.
*
* @example
* ```typescript
* const nestedObj = { a: { b: { c: 1 } } };
* const flatObj = flatObject({}, nestedObj);
* console.log(flatObj); // Outputs: { 'a.b.c': 1 }
* ```
*
* 또는 커링을 사용하여 함수를 반환할 수 있습니다.
*
* @param params - 평탄화 작업에 필요한 매개변수
* @returns 평탄화 작업을 수행하는 함수. 이 함수는 T 타입의 객체를 받아 평탄화된 객체를 반환합니다.
*
* @example
* ```typescript
* const flatten = flatObject({});
* const nestedObj = { a: { b: { c: 1 } } };
* const flatObj = flatten(nestedObj);
* console.log(flatObj); // Outputs: { 'a.b.c': 1 }
* ```
*/
declare const flatObject: {
<T extends RecursiveObj<any>, V = T extends RecursiveObj<infer U> ? U : never>(params: FlatObjectParams<T, V>, obj: T): Record<string, V>;
<T extends RecursiveObj<any>, V = T extends RecursiveObj<infer U> ? U : never>(params: FlatObjectParams<T, V>): (obj: T) => Record<string, V>;
};
/**
* 주어진 객체에서 빈 객체를 제거하는 함수입니다.
*
* @category Utils/Object
* @typeParam T - 어떤 키와 값을 가진 객체의 타입
*
* @param obj - 빈 객체를 제거할 대상 객체
* @returns 빈 객체가 제거된 새로운 객체
*
* @example
* ```typescript
* const obj = { a: { b: {} }, c: 1 };
* const result = removeEmptyObject(obj);
* console.log(result); // Outputs: { c: 1 }
* ```
*/
declare const removeEmptyObject: <T extends Record<any, any>>(obj: T) => T;
/**
* 데이터의 양을 나타내는 바이트 단위를 나타내는 타입입니다.
*
* @category Types/Static
*/
type ByteUnit = 'B' | 'KB' | 'MB' | 'GB' | 'TB';
/**
* 함수의 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam P - 함수에 전달될 매개변수의 타입 배열
* @typeParam R - 함수의 반환값의 타입
* @param params - 함수에 전달될 매개변수들
* @returns 함수의 반환값
*
* @example
* ```typescript
* // 함수의 타입 정의
* type AddFn = Fn<[x: number, y: number], number>;
*
* // 함수의 사용 예시
* const add: AddFn = (x, y) => x + y;
* ```
*/
type Fn<P extends any[] = any[], R = any> = (...params: P) => R;
/**
* 비동기 함수의 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam P - 함수에 전달될 매개변수의 타입 배열
* @typeParam R - 함수의 반환값의 타입
* @returns 비동기 함수의 반환값을 나타내는 Promise를 반환하는 함수 타입
*
* @example
* ```typescript
* // 비동기 함수의 타입 정의
* type FetchData = AsyncFn<[url: string], string>;
*
* // 비동기 함수의 사용 예시
* const fetchData: FetchData = async (url) => {
* const response = await fetch(url);
* return response.text();
* };
* ```
*/
type AsyncFn<P extends any[] = any[], R = any> = Fn<P, Promise<R>>;
/**
* 비동기 함수의 반환값 타입을 추출합니다.
*
* @category Types/Utility
*
* @typeParam T - 비동기 함수의 타입
* @returns 비동기 함수의 반환값의 타입
*
* @example
* ```tsx
* type Example = AsyncFnReturn<() => Promise<number>>;
* // type Example = number
* ```
*/
type AsyncFnReturn<T extends AsyncFn> = Awaited<ReturnType<T>>;
/**
* 객체의 모든 속성에서 readonly 를 제거합니다.
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입
* @returns 모든 속성의 readonly 가 제거된 객체의 타입
*
* @example
* ```typescript
* // 모든 속성의 readonly 가 제거된 객체의 타입 정의
* type MutablePerson = Mutable<{
* readonly name: string;
* readonly age: number;
* }>;
*
* type MutablePerson = {
* name: string;
* age: number;
* }
* ```
*/
type Mutable<T extends Record<any, any> | undefined> = {
-readonly [key in keyof T]: T[key];
};
/**
* 객체의 모든 속성에서 readonly 를 제거해줍니다.
*
* @category Types/Utility
*
* @typeParam T - 객체 타입
* @returns 모든 속성 readonly 가 제거 된 객체의 타입
*
* @example
* ```tsx
* type Example = DeepMutable<{
* readonly a: number;
* readonly b: { readonly c: number; readonly d: string };
* }>;
*
* // type Example = {
* // a: number;
* // b: { c : number; d : string };
* // }
* ```
*/
type DeepMutable<T extends Record<any, any> | undefined> = Mutable<{
[K in keyof T]: T[K] extends Record<any, any> | undefined ? Mutable<T[K]> : T[K];
}>;
/**
* 키와 값의 타입이 있는 객체의 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam K - 객체의 키 타입
* @typeParam V - 객체의 값 타입
*
* @example
* ```typescript
* // 객체의 타입 정의
* type Person = Obj<'name' | 'age', string | number>;
*
* // 객체의 사용 예시
* const person: Person = {
* name: 'Alice',
* age: 30,
* };
* ```
*/
type Obj<K extends string | number | symbol = string | number | symbol, V = unknown> = Record<K, V>;
/**
* 객체의 모든 속성을 nullable 하게 합니다.
*
* @category Types/Utility
*
* @typeParam T - nullable 한 속성을 추출할 객체의 타입
* @returns 모든 속성이 nullable 한 객체의 타입
* @example
* ```tsx
* type Example = NullAble<{ a: 1; b: 1 }>;
* // type Example = { a: 1 | null; b: 1 | null}
* ```
*/
type NullAble<T extends Obj | undefined> = {
[P in keyof T]: T[P] | null;
};
/**
* 객체의 모든 속성을 null 가능하게 만드는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - null 가능한 속성을 추출할 객체의 타입
* @returns 모든 속성이 null 가능한 객체의 타입
*
* @example
* ```typescript
* type NullablePerson = DeepNullable<{
* name: string;
* age: number;
* address: {
* city: string;
* postalCode: number;
* };
* }>;
* // type NullablePerson = {
* // name: string | null;
* // age: number | null;
* // address: {
* // city: string | null;
* // postalCode: number | null;
* // } | null;
* // }
* ```
*/
type DeepNullAble<T extends Obj | undefined> = NullAble<{
[K in keyof T]: T[K] extends Obj | undefined ? NullAble<T[K]> : T[K];
}>;
/**
* 두 개의 타입이 동일한지를 확인하고, 동일하다면 지정된 타입으로, 그렇지 않다면 다른 타입으로 설정하는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam X - 비교할 첫 번째 타입
* @typeParam Y - 비교할 두 번째 타입
* @typeParam A - 두 타입이 동일한 경우의 반환 타입 (기본값: 첫 번째 타입)
* @typeParam B - 두 타입이 동일하지 않은 경우의 반환 타입 (기본값: never)
* @returns 두 타입이 동일한 경우 A 타입을, 그렇지 않은 경우 B 타입을 반환합니다.
*
* @example
* ```typescript
* // 두 타입이 동일한 경우
* type Result1 = IfEquals<number, number, 'Equal', 'Not Equal'>;
* // type Result1 = 'Equal'
*
* // 두 타입이 동일하지 않은 경우
* type Result2 = IfEquals<number, string, 'Equal', 'Not Equal'>;
* // type Result2 = 'Not Equal'
* ```
*/
type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B;
/**
* 객체의 readonly 한 속성의 키를 추출합니다.
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입
* @returns 객체의 readonly 한 속성의 키들의 유니온 타입
*
* @example
* ```tsx
* type Example = ReadonlyKeysOf<{
* readonly a: number;
* b: string;
* readonly c: string;
* }>;
*
* // type Example = "a" | "c"
* ```
*/
type ReadonlyKeysOf<T extends object> = {
[P in keyof T]-?: IfEquals<{
[Q in P]: T[P];
}, {
-readonly [Q in P]: T[P];
}, never, P>;
}[keyof T];
/**
* 객체의 모든 읽기 전용 속성을 제거하는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - 읽기 전용 속성을 제거할 객체의 타입
* @returns 모든 읽기 전용 속성이 제거된 객체의 타입
*
* @example
* ```typescript
* type MutablePerson = DeepOmitReadOnly<{
* readonly name: string;
* readonly age: number;
* address: {
* readonly city: string;
* postalCode: number;
* };
* }>;
* // type MutablePerson = {
* // address: {
* // postalCode: number;
* // };
* // }
* ```
*/
type DeepOmitReadOnly<T extends Obj | undefined> = Omit<{
[P in keyof T]: T[P] extends Obj | undefined ? DeepOmitReadOnly<NonNullable<T[P]>> : T[P];
}, ReadonlyKeysOf<NonNullable<T>>>;
/**
* 객체의 모든 속성을 옵셔널하게 만듭니다
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입
* @returns 모든 속성이 옵셔널하게 만들어진 객체의 타입
*
* @example
* ```tsx
* type Example = DeepPartial<{
* a: number;
* b: { c : number; d : string };
* }>;
*
* Example = {
* a?: number;
* b?: { c? : number; d? : string };
* }
* ```tsx
*/
type DeepPartial<T extends Obj | undefined> = Partial<{
[K in keyof T]: T[K] extends Obj | undefined ? Partial<T[K]> : T[K];
}>;
/**
* 배열 또는 읽기 전용 배열의 요소 타입을 추출하는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - 요소 타입을 추출할 배열의 타입
* @returns 배열의 요소 타입
*
* @example
* ```typescript
* // 배열의 요소 타입 추출
* type Element = ItemOf<[string, number, boolean]>;
* // type Element = string | number | boolean
* ```
*/
type ItemOf<T extends Array<any> | readonly any[]> = T[number];
/**
* 객체에서 읽기 전용 속성을 제거합니다
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입
* @returns 읽기 전용 속성이 제거된 객체의 타입
*
* @example
* ```tsx
* type Example = OmitReadOnly<{
* readonly a: number;
* b: string;
* readonly c: string;
* }>;
*
* // type Example = { b : string; }
* ```
*/
type OmitReadOnly<T extends Obj> = Omit<T, ReadonlyKeysOf<T>>;
/**
* 함수의 첫번째 인자 타입을 가져옵니다.
*
* @category Types/Utility
*
* @typeParam T - 함수 타입
* @returns 함수의 첫번째 인자 타입
*
* @example
* ```tsx
* type Example = Parameter<(value: number) => void>
* // type Example = number
* ```
*/
type Parameter<T> = T extends (param: infer U) => any ? U : never;
/**
* 객체의 모든 속성의 타입을 추출합니다
*
* @category Types/Utility
*
* @typeParam T - 객체의 타입
* @returns 객체의 모든 속성의 타입
*
* @example
* ```tsx
* type Example = ValueOf<{ a: number; b: string }>;
*
* // type Example = number | string
* ```
*/
type ValueOf<T> = T extends Obj ? T[keyof T] : unknown;
/**
* 객체에서 모든 property 가 NonNullable 타입이 되도록 합니다.
*
* @category Types/Utility
*
* @typeParam T - NonNullable 타입으로 만들 객체의 타입
* @returns 모든 property 가 NonNullable 타입이 되도록 만들어진 객체의 타입
*
* @example
* type Example = NonNullableProps<{ a: 1 | null; b?: 1 }>;
* // type Example = { a: 1; b: 1 }
*/
type NonNullableProps<T extends Obj> = Omit<T, keyof T> & {
[P in keyof T]-?: NonNullable<T[P]>;
};
/**
* 데이터 또는 함수를 나타내는 타입입니다.
*
* @category Types/Utility
*
* @typeParam T - 데이터 또는 함수의 타입
* @param prev - 이전 값을 받아 새로운 값을 반환하는 함수
* @returns 데이터 또는 함수
*
* @example
* ```tsx
* const data: DataOrFn<number> = 42; // 데이터
* const fn: DataOrFn<number> = (prev) => prev + 1; // 함수
* ```
*/
type DataOrFn$1<T> = T | ((prev: T) => T);
/**
* 객체의 모든 속성을 null 가능하게 만드는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - null 가능한 속성을 추출할 객체의 타입
* @returns 모든 속성이 null 가능한 객체의 타입
*
* @example
* ```typescript
* type NullablePerson = DeepNullable<{
* name: string;
* age: number;
* address: {
* city: string;
* postalCode: number;
* };
* }>;
* // type NullablePerson = {
* // name: string | null;
* // age: number | null;
* // address: {
* // city: string | null;
* // postalCode: number | null;
* // } | null;
* // }
* ```
*/
type DeepNonNullAble<T> = T extends Obj | Array<any> ? {
[K in keyof T]-?: DeepNonNullAble<T[K]>;
} : Exclude<T, null | undefined>;
/**
* 배열의 인덱스 타입을 추출하는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - 인덱스 타입을 추출할 배열의 타입
* @returns 배열의 인덱스 타입
*
* @example
* ```typescript
* // 배열의 인덱스 타입 추출
* type Index = Indices<[string, number, boolean]>;
* // type Index = 0 | 1 | 2
* ```
*/
type Indices<T extends readonly any[]> = Extract<keyof T, `${number}`> extends never ? number : Extract<keyof T, `${number}`>;
/**
* 객체의 깊은 키를 나타내는 타입을 추출합니다.
*
* @category Types/Utility
*
* @typeParam T - 깊은 키를 추출할 객체의 타입
* @returns 객체의 깊은 키를 나타내는 타입
*
* @example
* ```typescript
* type DeepKeys = DeepKeyOf<{
* a: {
* b: number;
* c: {
* d: string[];
* };
* };
* }>;
* // type DeepKeys = 'a' | 'a.b' | 'a.c' | 'a.c.d' | `a.c.d.${number}`
* ```
*/
type DeepKeyOf<T, ExactT = DeepNonNullAble<T>> = ExactT extends Array<any> ? {
[K in Indices<ExactT>]: K extends number | string ? ExactT[K] extends Obj | Array<any> ? K | `${K}.${DeepKeyOf<ExactT[K]>}` : K : K;
}[Indices<ExactT>] : ExactT extends Obj ? {
[K in keyof ExactT]: K extends string | number ? K | `${ExactT[K] extends Obj | Array<any> ? `${K}.${DeepKeyOf<ExactT[K]>}` : never}` : never;
}[keyof ExactT] : never;
/**
* 객체의 깊은 속성 값을 추출하는 타입을 정의합니다.
*
* @category Types/Utility
*
* @typeParam T - 깊은 속성 값을 추출할 객체의 타입
* @typeParam K - 추출할 속성의 경로를 나타내는 타입
* @returns 객체의 깊은 속성 값의 타입
*
* @example
* ```typescript
* type Example = {
* a: {
* b: number;
* c: {
* d: string[];
* };
* };
* }
*
* // 객체의 깊은 속성 값 타입 추출
* type Value = DeepValueOf<Example, 'a.c.d'>;
* // type Value = string[]
* ```
*/
type DeepValueOf<T, K extends DeepKeyOf<T> | (string & {}) | number> = K extends keyof T ? T[K] : K extends `${infer Key}.${infer Rest}` ? T extends Array<any> ? Key extends `${number}` ? DeepValueOf<T[`${number}`], Rest> : never : Key extends keyof T ? undefined extends T[Key] ? DeepValueOf<NonNullable<T[Key]>, Rest> | undefined : null extends T[Key] ? DeepValueOf<NonNullable<T[Key]>, Rest> | undefined : DeepValueOf<T[Key], Rest> : never : never;
/**
* `MockedFn`은 Jest의 mock 함수를 타입으로 나타내는 유틸리티 타입입니다.
* @category Types/Utility
* @typeParam T - 어떤 매개변수를 받고 어떤 값을 반환하는 함수의 타입
*
* 이 타입은 `T` 타입의 함수와 같은 매개변수를 받고 같은 타입의 값을 반환하는 Jest의 mock 함수의 타입을 나타냅니다.
* 이 타입은 Jest의 mock 함수를 타입 체크할 때 사용할 수 있습니다.
*
* @example
* ```typescript
* const mockFn: MockedFn<(a: number, b: number) => number> = jest.fn((a, b) => a + b);
* ```
*/
type MockedFn<T extends (...params: any) => any> = jest.Mock & ((...args: Parameters<T>) => ReturnType<T>);
/**
* 넘겨진 key 를 기반으로, 객체의 type 을 만들어 줍니다.
*
* @category Types/Utility
*
* @typeParam T - key 값
* @typeParam Value - 해당 key 의 값의 타입 (default: any)
*
* @example
* ```ts
* type A = ObjSchemaByKey<'a.b.c'> // { a?: { b?: { c?: any } } }
* type B = ObjSchemaByKey<'a.b.0.title'> // { a?: { b?: {title?: any}[] } }
*
*/
type ObjSchemaByKey<T extends string | number, Value = any> = T extends `${infer Key}.${infer Rest}` ? Key extends `${number}` ? ObjSchemaByKey<Rest, Value>[] : {
[K in Key]?: ObjSchemaByKey<Rest, Value>;
} : {
[K in T]?: Value;
};
type DataOrFn<T, D> = T | ((prev: T, origin: D) => T);
/**
* @deprecated
* use `update` instead
*
* 객체의 지정된 깊은 위치에 값을 설정하거나 업데이트합니다.
*
* @category Utils/Object
*
* @typeParam T - 입력 객체의 타입
* @typeParam K - 설정 또는 업데이트할 속성의 깊은 경로를 나타내는 키
* @param key - 설정 또는 업데이트할 속성의 깊은 경로를 나타내는 키
* @param value - 설정할 값 또는 값을 반환하는 함수
* @param obj - 값을 설정 또는 업데이트할 객체
* @returns 값을 설정 또는 업데이트한 객체
*
* @example
* ```typescript
* const data = { nested: { prop: 42 } };
*
* // 객체의 깊은 경로에 값을 설정
* const updated1 = updateObj('nested.prop', 100, data); // { nested: { prop: 100 } }
*
* // 함수를 사용하여 값을 설정
* const updated2 = updateObj('nested.prop', (prev) => prev + 1, data); // { nested: { prop: 43 } }
*
* // 원본 객체의 다른 값을 참조하여 값을 설정
* const updated3 = updateObj('nested.prop', (prev, obj) => prev + obj.nested.prop, data); // { nested: { prop: 84 } }
*
* // 함수를 부분 적용하여 사용
* const updater = updateObj('nested.prop');
* const updated4 = updater(200)(data); // { nested: { prop: 200 } }
* ```
*
*
* @curried
*/
declare const updateObj: {
<T, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K, value: DataOrFn<DeepValueOf<T, K>, T>, obj: T): T;
<T, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K): (value: DataOrFn<DeepValueOf<T, K>, T>) => (obj: T) => T;
<T, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K, value: DataOrFn<DeepValueOf<T, K>, T>): (obj: T) => T;
};
type ObjSelector<T, N = any> = (prev: T) => N;
type ObjSelectorMap<T> = Record<string, ObjSelector<T>>;
type ObjSelectorMapResult<T, M extends ObjSelectorMap<T>> = {
[K in keyof M]: ReturnType<M[K]>;
};
/**
* 객체에서 선택된 속성을 기반으로 새로운 객체를 생성합니다.
* @category Utils/Object
* @typeParam T - 입력 객체의 타입
* @typeParam N - 생성된 객체의 각 속성 값의 타입
* @typeParam M - 선택된 속성과 반환값의 매핑
* @param mapper - 선택된 속성과 각 속성 값의 생성 함수로 이루어진 매핑 객체
* @param prev - 입력 객체
* @returns 선택된 속성을 기반으로 생성된 객체
*
* @example
* ```typescript
* const data = { a: 1, b: 2, c: 3 };
* const selectors = {
* sum: ({ a, b, c }) => a + b + c,
* product: ({ a, b, c }) => a * b * c,
* };
*
* const result = createObjBySelector(selectors, data);
* const result = createObjBySelector(selectors)(data);
*
* console.log(result); // { sum: 6, product: 6 }
* ```
*
* @curried
*/
declare const createObjBySelector: {
<T, M extends ObjSelectorMap<T> = ObjSelectorMap<T>>(mapper: M, prev: T): ObjSelectorMapResult<T, M>;
<T, M extends ObjSelectorMap<T> = ObjSelectorMap<T>>(mapper: M): (prev: T) => ObjSelectorMapResult<T, M>;
};
/**
* @category Utils/Object
*
* 객체의 key 에서 flag 를 찾아서 해당 flag 를 기준으로 중첩 객체를 만들어주는 함수입니다.
*
* @param flag - object 생성 기준이 되는 flag 입니다.
* @param obj - flag 를 기준으로 중첩 객체를 만들 객체입니다.
*
* @returns flag 를 기준으로 중첩 객체를 만들어 반환합니다.
*
* @example
* ```ts
* const obj = {
* a: 1,
* 'b.a': 2,
* 'b.b': 3,
* 'c.a.a': 6,
* }
*
* const result = volumeUpObject('.', obj)
*
* console.log(result)
*
* // {
* // a: 1,
* // b: {
* // a: 3,
* // b: 4,
* // },
* // c: {
* // a: {
* // a: 6,
* // },
* // },
* // }
* ```
*/
declare const volumeUpObject: {
(flag: string, obj: Obj): Obj;
(flag: string): (obj: Obj) => Obj;
};
/**
* 객체의 property 를 key 로 받아서 값을 가져오는 함수입니다.
* 중접 객체의 경우 a.b.c 와 같이, 배열의 경우 a.0.b 와 같이 접근이 가능합니다.
*
*
* @category Utils/Fn
*
* @typeParam T - 객체의 타입
* @typeParam K - 객체의 key
* @param key - 객체의 key
* @param data - 객체 혹은 배열
* @returns 객체의 key 에 해당하는 값
*
* @example
* ```ts
*
* const data = {
* user: {
* name: 'John Doe',
* address: {
* city: 'New York',
* },
* posts: [
* { title: 'Post 1' },
* { title: 'Post 2' },
* ],
* }
*
* // 객체의 key 에 해당하는 값 가져오기
* get('user.name', data) // 'John Doe'
* get('user.address.city', data) // 'New York'
*
* // 배열의 key 에 해당하는 값 가져오기
* get('posts.0.title', data) // 'Post 1'
*
* // curried function 으로 사용하기
* const getUserName = get('user.name')
* getUserName(data) // 'John Doe'
*
* const logname = flow(get('user.name'), console.log)
* logname(data) // 'John Doe'
*
* const name = useStore(get('user.name')) // 'John Doe'
*
* ```
*/
declare const get: {
<T extends Obj | Array<any>, K extends DeepKeyOf<T>>(key: K, data: T): DeepValueOf<T, K>;
<T extends Obj | Array<any>, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K): <_T extends ObjSchemaByKey<K>>(data: _T) => DeepValueOf<_T, K>;
};
type DataOrSetterFn<T, D> = T | ((prev: T, get: <K extends DeepKeyOf<T>>(key: K) => DeepValueOf<T, K>, origin: D) => T);
/**
* 객체의 지정된 깊은 위치에 값을 설정하거나 업데이트합니다.
*
* @category Utils/Object
*
* @typeParam T - 입력 객체의 타입
* @typeParam K - 설정 또는 업데이트할 속성의 깊은 경로를 나타내는 키
* @param key - 설정 또는 업데이트할 속성의 깊은 경로를 나타내는 키
* @param value - 설정할 값 또는 값을 반환하는 함수
* @param obj - 값을 설정 또는 업데이트할 객체
* @returns 값을 설정 또는 업데이트한 객체
*
* @example
* ```typescript
* const data = { nested: { prop: 42 } };
*
* // 객체의 깊은 경로에 값을 설정
* const updated1 = set('nested.prop', 100, data); // { nested: { prop: 100 } }
*
* // 함수를 사용하여 값을 설정
* const updated2 = set('nested.prop', (prev) => prev + 1, data); // { nested: { prop: 43 } }
*
* // 원본 객체의 다른 값을 참조하여 값을 설정
* const updated3 = set('nested.prop', (prev, obj) => prev + obj.nested.prop, data); // { nested: { prop: 84 } }
*
* // 함수를 부분 적용하여 사용
* const updater = set('nested.prop');
* const updated4 = updater(200)(data); // { nested: { prop: 200 } }
* ```
*
*
* @curried
*/
declare const update: {
<T extends Obj | Array<any>, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K, value: DataOrSetterFn<DeepValueOf<T, K>, T>, obj: T): T;
<T extends Obj | Array<any>, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K, value: DataOrSetterFn<DeepValueOf<T, K>, T>): (obj: T) => T;
<T extends Obj | Array<any>, K extends DeepKeyOf<T> = DeepKeyOf<T>>(key: K): {
(value: DataOrSetterFn<DeepValueOf<T, K>, T>): (obj: T) => T;
(value: DataOrSetterFn<DeepValueOf<T, K>, T>, obj: T): T;
};
};
/**
* 주어진 값이 함수인 경우 주어진 인자들을 사용하여 실행하고, 그렇지 않으면 주어진 값을 그대로 반환합니다.
*
* @category Utils/Fn
*
* @typeParam T - 반환할 값의 타입
* @typeParam U - 함수의 매개변수의 타입
* @param valueOrFn - 실행할 함수 또는 반환할 값
* @param args - 함수에 전달할 매개변수
* @returns 주어진 값이 함수인 경우 주어진 인자들을 사용하여 실행한 결과를 반환하고, 그렇지 않으면 주어진 값을 그대로 반환합니다.
*
* @example
* ```ts
* const add = (a: number, b: number) => a + b;
* runIfFn(add, 2, 3); // 5 - add 함수를 실행하여 결과를 반환합니다.
* runIfFn(5, 2, 3); // 5 - 주어진 값이 함수가 아니므로 주어진 값을 그대로 반환합니다.
* ```
*/
declare function runIfFn<T, U>(valueOrFn: T | ((...fnArgs: U[]) => T), ...args: U[]): T;
/**
*
* 함수를 실행하고, 인자를 그대로 반환합니다.
* 컴포넌트 합성시(lodash.flow) 함수의 응닶값에 영향을 미치지 않고 특정 함수를 실행시키고 싶을 경우 유용합니다.
*
* @category Utils/Fn
*
* @typeParam T - 함수에 전달할 인자의 타입
* @param fn - 실행할 함수
* @param x - 실행할 함수에 전달할 인자
* @returns 실행할 함수에 전달한 인자
*
* @example
* ```ts
* effect(console.log, 'hello') // 'hello'를 출력하고 'hello'를 반환합니다.
*
* effect(console.log)('hello') // 'hello'를 출력하고 'hello'를 반환합니다.
*
* const log = effect(console.log)
* log('hello') // 'hello'를 출력하고 'hello'를 반환합니다.
*
* const dotToDash = flow(split("."), effect(console.log), join('-'))
* dotToDash('a.b.c') // ['a', 'b', 'c'] 를 출력하고 'a-b-c'를 반환합니다.
* ```
* @curried
*/
declare const effect: {
<T>(fn: (x: T) => void, x: T): T;
<T>(fn: (x: T) => void): (x: T) => T;
};
/**
* @category Utils/Fn
*
* Promise 를 받아 resolve 된 값으로 함수를 실행합니다.
*
* @example
* ```ts
* const double = (x: number) => x * 2
* const target = 5
* const targetPromise = Promise.resolve(5)
*
* const result = awaited(double, target) // 10
* const resultPromise = awaited(double, targetPromise) // 10
*
* // curried
* flow(() => Promise.resolve(5), awaited(double))
* ```
*/
declare const awaited: {
<P, R>(fn: (p: P) => R, data: P | PromiseLike<P>): Promise<R>;
<P, R>(fn: (p: P) => R): (data: P | PromiseLike<P>) => Promise<R>;
};
/**
* 주어진 데이터를 반환하는 함수를 생성합니다.
*
* @category Utils/Fn
*
* @typeParam T - 반환할 데이터의 타입
* @param data - 반환할 데이터
* @returns 주어진 데이터를 반환하는 함수
*
* @example
* ```typescript
* const data = { id: 1, name: 'John' };
* const getData = pass(data);
* const result = getData(); // { id: 1, name: 'John' }
* ```
*/
declare const pass: <T>(data: T) => () => T;
/**
* 주어진 값이 null 또는 undefined인 경우 기본값을 반환하고, 그렇지 않으면 주어진 값을 반환합니다.
*
* @category Utils/Fn
*
* @typeParam T - 반환할 값의 타입
* @param def - 기본값
* @param value - 확인할 값
* @returns 주어진 값이 null 또는 undefined인 경우 기본값을 반환하고, 그렇지 않으면 주어진 값을 반환합니다.
*
* @example
* ```ts
* or(0, 5); // 5 - 5는 null 또는 undefined가 아니므로 그대로 반환됩니다.
* or(0, null); // 0 - null이므로 기본값 0이 반환됩니다.
* or(0, undefined); // 0 - undefined이므로 기본값 0이 반환됩니다.
*
* or(0)(5) // 5
* or(0)(null) // 0
* or(0)(undefined) // 0
*
* const isEven = (x: number) => x % 2 === 0;
*
* const isOddOrZero = flow(
* not(isEven), // 짝수가 아닌 값들을 거름
* or(0) // null 또는 undefined인 경우 0으로 대체
* );
*
* // 예시
* console.log(isOddOrZero(5)); // 5 - 홀수는 그대로 반환됩니다.
* console.log(isOddOrZero(10)); // 0 - 짝수는 0으로 대체됩니다.
* console.log(isOddOrZero(null)); // 0 - null은 0으로 대체됩니다.
* ```
*
* @curried
*/
declare const or: {
<T>(def: T, value: T | null | undefined): T;
<T>(def: T): (value: T | null | undefined) => T;
};
/**
* 여러 함수들이 모두 주어진 인자에 대해 true를 반환하는지 확인합니다.
* 주어진 함수 배열(fns)에 대해 모든 함수가 인자를 받아들여 true를 반환하는지 여부를 검사합니다.
*
* @category Utils/Fn
*
* @typeParam T - 함수에 전달할 인자의 타입
* @param fns - 평가할 함수들의 배열
* @returns 모든 함수가 인자를 받아들여 true를 반환하는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.
*
* @example
* ```ts
* const isPositive = (x: number) => x > 0;
* const isEven = (x: number) => x % 2 === 0;
* const isGreaterThanTen = (x: number) => x > 10;
*
* const conditions = [isPositive, isEven, isGreaterThanTen];
*
* isEvery(conditions)(4); // false - 4는 isGreaterThanTen의 조건을 만족하지 않습니다.
* isEvery(conditions)(12); // true - 모든 조건을 만족합니다.
* ```
* @curried
*/
declare const isEvery: <T extends any[]>(fns: ((...param: T) => boolean)[]) => (...param: T) => boolean;
/**
* 주어진 함수의 부정값을 반환합니다.
* 주어진 함수를 실행하고 그 결과를 부정하여 반환합니다.
*
* @category Utils/Fn
*
* @typeParam T - 함수의 매개변수와 반환값의 타입
* @param fn - 부정할 함수
* @param args - 함수에 전달할 매개변수
* @returns 주어진 함수의 부정값을 반환합니다.
*
* @example
* ```ts
* const isPositive = (x: number) => x > 0;
* const isNegative = not(isPositive);
*
* isNegative(5); // false - isPositive(5)의 부정값이므로 false를 반환합니다.
* isNegative(-5); // true - isPositive(-5)의 부정값이므로 true를 반환합니다.
* ```
* @curried
*/
declare const not: <T extends (...params: any[]) => any>(fn: T) => (...args: Parameters<T>) => boolean;
/**
* @category Utils/Fn
*
* arguments 를 배열로써 반환합니다.
*
* @param args - arguments
*
* @returns arguments 를 배열로써 반환합니다.
*
* @example
* ```ts
* collect(1, 2, 3) // [1, 2, 3]
* ```
*/
declare const collect: <T>(...args: T[]) => T[];
declare const delay: (ms: number, option?: {
success?: any;
error?: any;
}) => Promise<unknown>;
type RetryFnParams<T = any, E = any> = {
getToken: () => Promise<string>;
onRefetch: (refresed: string) => T;
onError?: (error: E) => void;
};
/**
* @category Utils/Fn
*
* 주로 refresh token 이 필요한 요청을 관리하는 함수입니다.
* 토큰이 만료됐을 시, refresh token 을 요청하고, 새로운 토큰을 받아서 요청을 재시도합니다.
*
* @returns refresh token 이 필요한 요청을 관리하는 함수입니다.
*
* @example
*
* ```ts
* const retry = retryReqeustManager()
*
* const result = await retry({
* getToken: async () => {
* await delay(200)
* return 'token'
* },
* onRefetch: (token: string) => {
* return token
* },
* onError: (error: any) => {
* return error
* },
* })
*
*
*/
declare const retryReqeustManager: () => <T, E>(params: RetryFnParams<T, E>) => Promise<T>;
interface RelayParams<Data, NextParam, Selected> {
/**
* 첫번째 호출시 넘겨줄 파라미터입니다.
*/
initialParam: NextParam;
/**
* 다음 데이터를 가져오는 함수입니다.
* getNextParams 으로 부터 받은 파라미터를 이용하여 데이터를 가져옵니다.
* getNextParams 가 null 을 반환하면 getNext 는 호출되지 않습니다.
*
* @param nextParam - 다음 데이터를 가져오기 위한 파라미터
*/
getNext: (nextParam: NextParam) => Promise<Data>;
/**
* 다음 데이터를 가져오기 위한 파라미터를 반환하는 함수입니다.
* 이전 마지막으로 여청한 getNext 에서 받은 데이터를 이용하여 다음 데이터를 가져오기 위한 파라미터를 반환합니다.
* null 을 반환하면, 데이터를 가져오는 것을 중지합니다.
*
* @param last - 마지막으로 가져온 데이터
*/
getNextParams: (last: Data) => NextParam | null;
/**
* 각 페이지별 데이터를 포메팅하여 원하는 형태의 데이터를 반환하게끔 합니다.
* @param data - 가져온 데이터
*/
selector?: (data: Data[]) => Selected;
}
/**
* @category Utils/Fn
*
* 인자로 넘겨준 getNext 함수를 연속적으로 호출하여 데이터를 가져오는 함수입니다.
* 호출된 데이터를 순서대로 배열로 반환합니다.
*
* 주로 pagination 된 데이터의 모든 페이지를 가져오는데 사용됩니다.
*
* @example
*
* ```ts
* const list = range(0, 100)
*
* const getList = async (params: { offset: number; limit: number }) => {
* const { offset, limit } = params
* const next = offset + limit
*
* return {
* total: list.length,
* next: list.length - 1 < next ? null : next,
* data: list.slice(offset, offset + limit),
* }
*
* const result = await relay({
* initialParam: 0,
* getNext: (nextParam: number) => getList({ offset: nextParam, limit: 10 }),
* getNextParams: (last) => {
* return last?.next
* },
*
* console.log(result)
*
* // [
* // { total: 100, next: 10, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] },
* // { total: 100, next: 20, data: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] },
* // { total: 100, next: 30, data: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29] },
* // ...
* // { total: 100, next: null, data: [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] },
* // ]
*
*
* ```
*/
declare const relay: <Data, NextParam, Selected = Data[]>(params: RelayParams<Data, NextParam, Selected>) => Promise<Selected>;
/**
* @curried
* @category Functor
*/
declare class Keep_F<Kept, Value> {
kept: Kept;
value: Value;
constructor(kept: Kept, value: Value);
of: <New>(value: New) => Keep_F<Kept, New>;
map: <New>(fn: (value: Value, kept: Kept) => New) => Keep_F<Kept, New>;
}
/**
* @category Functor
*/
declare const keep: {
<T>(kept: T): Keep_F<T, T>;
of: {
<Kept, Value>(value: Value, keep: Keep_F<Kept, Value>): Keep_F<Kept, Value>;
<Kept, Value>(value: Value): (keep: Keep_F<Kept, Value>) => Keep_F<Kept, Value>;
};
map: {
<Kept, Prev, New>(fn: (value: Prev, kept: Kept) => New, keep: Keep_F<Kept, Prev>): Keep_F<Kept, New>;
<Kept, Prev, New>(fn: (value: Prev, kept: Kept) => New): (keep: Keep_F<Kept, Prev>) => Keep_F<Kept, New>;
};
value: <Kept, Value>(keep: Keep_F<Kept, Value>) => Value;
};
/**
* @category Functor
*/
declare class Maybe_F<T> {
static of: <T_1>(x: T_1) => Maybe_F<T_1>;
$value: T | null | undefined;
get isNothing(): boolean;
constructor($value: T | null | undefined);
map: <R>(fn: (value: T) => R) => Maybe_F<R>;
}
/**
* @category Functor
*/
declare const maybe: (<T>(value: T) => Maybe_F<T>) & {
map: <T, R>(fn: (value: T) => R) => (maybe: Maybe_F<T>) => Maybe_F<R>;
value: <T>(maybe: Maybe_F<T>) => T | null | undefined;
};
/**
* 문자열에서 지정된 문자열을 제거합니다.
*
* @category Utils/String
*
* @param str - 제거할 문자열
* @param s - 대상 문자열
* @returns 지정된 문자열이 제거된 결과 문자열
*
* @example
* ```typescript
* const removedStr1 = removeStr('a', 'banana'); // 'bnn'
* console.log(removedStr1);
*
* const removeA = removeStr('a'); // 부분 적용
* const removedStr2 = removeA('apple'); // 'pple'
* console.log(removedStr2);
*
* const removedStr3 = removeStr(' ', 'hello world'); // 'helloworld'
* console.log(removedStr3);
* ```
*
* @curried
*/
declare const removeStr: {
(str: string | RegExp, s: string): string;
(str: string | RegExp): (s: string) => string;
};
/**
* 문자열에 접두사를 추가합니다.
*
* @category Utils/String
* @param pre - 접두사로 사용될 문자열
* @param str - 접두사를 추가할 대상 문자열
* @returns 접두사가 추가된 문자열
*
* @example
* ```typescript
* const prefixedStr1 = prefix('pre-', 'string'); // 'pre-string'
* console.log(prefixedStr1);
*
* const prefixWithHello = prefix('Hello, '); // 부분 적용
* const prefixedStr2 = prefixWithHello('world!'); // 'Hello, world!'
* console.log(prefixedStr2);
*
* const prefixedStr3 = prefix('1. ')('First item'); // '1. First item'
* console.log(prefixedStr3);
* ```
*
* @curried
*/
declare const prefix: {
(pre: string, str: string): string;
(pre: string): (str: string) => string;
};
/**
* 문자열에 접미사를 추가합니다.
*
* @category Utils/String
*
* @param suf - 접미사로 사용될 문자열
* @param str - 접미사를 추가할 대상 문자열
* @returns 접미사가 추가된 문자열
*
* @example
* ```typescript
* const suffixedStr1 = suffix('-post', 'string'); // 'string-post'
* console.log(suffixedStr1);
*
* const suffixWithDot = suffix('.'); // 부분 적용
* const suffixedStr2 = suffixWithDot('extension'); // 'extension.'
* console.log(suffixedStr2);
*
* const suffixedStr3 = suffix('!', 'Hello'); // 'Hello!'
* console.log(suffixedStr3);
* ```
*
* @curried
*/
declare const suffix: {
(suf: string, str: string): string;
(suf: string): (str: string) => string;
};
/**
* 주어진 값을 로깅하고 반환합니다.
*
* @category Utils/Logger
*
* @typeParam T - 로깅할 값의 타입
* @param title - 로그 제목
* @param value - 로깅할 값
* @returns 주어진 값
*
* @example
* ```typescript
* const result = log('Result:', 42); // Result: 42
* const result = log('Result:')(42); // Result: 42
*
* const ex = flow(
* add(1),
* log('debug:'), // debug
* add(2)
* )
*
* ex(1) debug: 2
*
* ```
*
* @curried
*/
declare const log: {
<T>(title: string, value: T): T;
<T>(title: string): (value: T) => T;
};
/**
* @category Utils/Math
*
* 숫자들의 소수점 자리수중 가장 긴 소수점 자리의 길이를 구합니다.
*
* @param numnbers - 소수점 자리수를 구할 숫자들
*
* @returns 소수점 자리수
* @example
* ```ts
* getDecimalPlaces(0.1, 0.2) // 1
* getDecimalPlaces(0.1, 0.02, 0.3) // 2
* getDecimalPlaces(0.1, 0.2, 0.333, 0.4) // 3
*/
declare const getDecimalPlaces: (...numnbers: number[]) => number;
/**
* @category Utils/Math
*
* 두개의 숫자를 더합니다. 부정확 할 수 있는 부동 소수점 연산을 보정합니다.
* @param a - 첫번째 숫자
* @param b - 두번째 숫자
*
* @returns 두 숫자를 더한 결과
*
* @example
* ```ts
* add(0.1, 0.2) // 0.3
* add(0.1)(0.2) // 0.3
* ```
*/
declare const add: {
(a: number, b: number): number;
(a: number): (b: number) => number;
};
/**
* @category Utils/Math
*
* 두개의 숫자를 뺍니다. 부정확 할 수 있는 부동 소수점 연산을 보정합니다.
*
* @param a - 첫번째 숫자
* @param b - 두번째 숫자
*
* @returns 두 숫자를 뺀 결과
*
* @example
* ```ts
* subtract(0.3, 0.1) // 0.2
* subtract(0.3)(0.1) // 0.2
* ```
*/
declare const subtract: {
(a: number, b: number): number;
(a: number): (b: number) => number;
};
/**
* @category Utils/Math
*
* 두개의 숫자를 곱합니다. 부정확 할 수 있는 부동 소수점 연산을 보정합니다.
*
* @param a - 첫번째 숫자
* @param b - 두번째 숫자
*
* @returns 두 숫자를 곱한 결과
*
* @example
* ```ts
* multiply(0.1, 0.2) // 0.02
* multiply(0.1)(0.2) // 0.02
* ```
*/
declare const multiply: {
(a: number, b: number): number;
(a: number): (b: number) => number;
};
/**
* @category Utils/Math
*
* 두개의 숫자를 나눕니다. 부정확 할 수 있는 부동 소수점 연산을 보정합니다.
*
* @param a - 첫번째 숫자
* @param b - 두번째 숫자
*
* @returns 두 숫자를 나눈 결과
*
* @example
* ```ts
* devide(0.3, 0.1) // 3
* devide(0.3)(0.1) // 3
* ```
*/
declare const devide: {
(a: number, b: number): number;
(a: number): (b: number) => number;
};
/**
* @category Utils/File
*
* 특정 바이트 단위를 바이트로 변환합니다.
*
* @param from - 변환할 바이트 단위
* @param value - 변환할 값
*
* @returns 변환된 바이트 값
*
* @example
* ```ts
* byteFrom('KB', 1) // 1024
* byteFrom('KB')(1) // 1024
* ```
*/
declare const byteFrom: {
(from: ByteUnit, value: number): number;
(from: ByteUnit): (value: number) => number;
};
/**
* @category Utils/File
*
* 바이트를 특정 바이트 단위로 변환합니다.
*
* @param to - 변환할 바이트 단위
* @param value - 변환할 값
*
* @returns 변환된 바이트 값
*
* @example
* ```ts
* byteTo('KB', 1024) // 1
* byteTo('KB')(1024) // 1
* ```
*/
declare const byteTo: {
(to: ByteUnit, value: number): number;
(to: ByteUnit): (value: number) => number;
};
/**
* @category Utils/File
*
* 특정 바이트 단위를 다른 바이트 단위로 변환합니다.
*
* @param from - 변환할 바이트 단위
* @param to - 변환될 바이트 단위
* @param value - 변환할 값
*
* @returns 변환된 바이트 값
*
* @example
* ```ts
* const KbToB = byteFromTo('KB', 'B')
* KbToB(1) // 1024
*
* const GBToMb = byteFromTo('gb', 'mb')
* GBToMb(1) // 1024
*
* byteFromTo('KB', 'B', 1) // 1024
* byteFromTo('KB')('B')(1) // 1024
* ```
*/
declare const byteFromTo: {
(from: ByteUnit, to: ByteUnit, value: number): number;
(from: ByteUnit, to: ByteUnit): (value: number) => number;
(from: ByteUnit): CurriedFunction2<ByteUnit, number, number>;
};
/**
* @category Utils/File
* 주어진 파일 크기가 최대 크기를 초과하는지 확인하는 함수입니다.
*
* @example
* ```ts
* // 값이 500바이트인 경우
* isOverSize([1000, 'B'], 500); // false
*
* // 커링 사용 예
* const isOver1MB = isOverSize([1, 'MB']);
* isOver1MB(500000); // true
* ```
*
* @param maxSize - 파일의 최대 크기
* @param value - 검사할 값. 바이트 단위의 숫자 또는 크기와 단위를 포함하는 배열
* @returns 값이 최대 크기를 초과하면 true, 그렇지 않으면 false
*/
declare const isOverSize: {
(maxSize: [value: number, unit: ByteUnit], value: number | [value: number, unit: ByteUnit]): boolean;
(maxSize: [value: number, unit: ByteUnit]): (value: number | [value: number, unit: ByteUnit]) => boolean;
};
interface CreateS3UploadFlowConfig<Input, S3Config, Result> {
/**
*
* 파일을 업로드하기 전에 필요한 정보를 준비합니다.
* - 주로 presigned url 을 생성하고, 필요한 정보를 준비합니다.
* - 해당 함수의 parameter type 은 이후 return 되는 uploadFile 함수의 input type 이 됩니다.
* - 해당 함수의 return type 은 `config.uploadFileToS3` 함수의 input type 이 됩니다.
*
*/
prepareUpload: (input: Input) => Promise<S3Config>;
/**
* S3에 파일을 업로드합니다.
* - 주로 s3 에 파일을 업로드합니다.
* - 해당 함수의 parameter type 은 `config.prepareUpload` 함수의 return type 이 됩니다.
* - 해당 함수의 return type 은 이후 return 되는 uploadFile 함수의 return type 이 됩니다.
*/
uploadFileToS3: (s3Config: S3Config) => Promise<Result>;
}
interface CreateS3UploadFlowReturn<Input, Result> {
/**
* 단일 파일을 업로드합니다.
*/
uploadFile: (input: Input) => Promise<Result>;
/**
* 다수의 파일을 업로드합니다.
*/
uploadFiles: (input: Input[]) => Promise<{
fulfilled: Result[];
rejected: PromiseRejectedResult[];
}>;
}
/**
* @category Utils/File
*
* createUploadFlow 함수는 S3 파일 업로드를 위한 플로우를 생성합니다.
*
* @example
*
* ```ts
* const { uploadFile, uploadFiles } = createUploadFlow({
* prepareUpload: async ({name} : {name : string}) => {
* return {
* name: name,
* type: "image",
* }
* },
* uploadFileToS3: async ({ name, type }) => {
* return { name, type, imgUrl: "https://example.com" }
* },
* })
*
* const result = await uploadFile({ name: "example" }) // { name: "example", type: "image", imgUrl: "https://example.com" }
* const results = await uploadFiles([{ name: "example" }, { name: "example2" }]) // { fulfilled: [{ name: "example", type: "image", imgUrl: "https://example.com" } , ...], rejected: [] }
* ```
*
*/
declare const createS3UploadFlow: <Input, S3Config, Result>(config: CreateS3UploadFlowConfig<Input, S3Config, Result>) => CreateS3UploadFlowReturn<Input, Result>;
declare const isNullish: <T>(value: T) => value is Extract<null | undefined, T>;
declare const isNotNullish: <T>(value: T) => value is NonNullable<T>;
type AssertItemOf = <T>(arr: T[] | readonly T[], type: unknown, message?: string) => asserts type is T;
declare const assertItemOf: AssertItemOf;
interface JwtDecodeOptions {
header?: boolean;
}
interface JwtHeader {
typ?: string;
alg?: string;
kid?: string;
}
interface JwtPayload {
iss?: string;
sub?: string;
aud?: string[] | string;
exp?: number;
nbf?: number;
iat?: number;
jti?: string;
}
declare class InvalidTokenError extends Error {
}
/**
*
* @category Utils/Decode
*
* @param token - target
* @param options - jwt decode option
*
* @returns decoded
*/
declare function jwtDecode<T = JwtHeader>(token: string, options: JwtDecodeOptions & {
header: true;
}): T;
declare function jwtDecode<T = JwtPayload>(token: string, options?: JwtDecodeOptions): T;
/**
* 고차 함수로 fetch를 확장합니다.
*
*/
/**
*
* @category Utils/Fetch
*
* fetch 함수의 args
*
* @throws {Error} 만약 fetch의 첫 번째 인자가 'Request' 객체인 경우에는 문자열과 URL만 지원됩니다.
* @see {@link https://developer.mozilla.org/ko/docs/Web/API/Fetch_API Fetch API}
* @see {@link https://developer.mozilla.org/ko/docs/Web/API/Request Request}
* @see {@link https://developer.mozilla.org/ko/docs/Web/API/Request/Request RequestInfo}
*
* @public
*/
type FetchArgs = [string | URL, RequestInit | undefined];
/**
*
* @category Utils/Fetch
*
* `fetchHelper` 함수의 타입입니다.
* 이는 사용자 지정 `fetchHelper` 함수를 작성하고자 할 때 유용합니다.
*
* @public
*/
type FetchHelperType = typeof fetchHelper;
/**
*
* @category Utils/Fetch
*
* `fetchHelper` 함수의 옵션입니다.
*
* @public
*/
interface FetchHelperDefaultOptions {
/**
* fetchHelper 함수에서 사용될 fetch 함수입니다.
* 제공되지 않으면 전역 스코프의 fetch 함수가 사용됩니다.
* node-fetch, cross-fetch 등과 같은 어떤 fetch 구현체라도 사용할 수 있습니다.
* 또한 fetchHelper에 의해 생성된 fetch 함수 또한 여기에서 사용할 수 있습니다.
*
* @public
*/
fetch?: ReturnType<FetchHelperType>;
/**
* fetch의 baseURL입니다.
*
* @public
*/
baseUrl?: string | URL;
/**
* fetch의 기본 헤더입니다. 만약 fetch의 두 번째 인자가 headers 속성을 가지고 있지 않은 경우 사용됩니다.
* 제공되고 fetch를 호출할 때 headers도 제공된 경우, 헤더가 병합됩니다.
* 헤더의 우선순위는 requestInit.headers > defaultOptions.headers입니다. 중복된 헤더는 덮어쓰기 됩니다.
*
* @public
*/
headers?: HeadersInit;
interceptors?: {
/**
* Request interceptor. Request 전에 호출됩니다.
*
* @param requestArgs fetch 함수의 인자들입니다.
* @param fetch {@link FetchHelperDefaultOptions['fetch']} 에서 제공한 `fetch` 입니다.
*
* @public
*/
request?: (requestArgs: FetchArgs, fetch: NonNullable<FetchHelperDefaultOptions['fetch']>) => Promise<FetchArgs>;
/**
* Response interceptor. Response 후에 호출됩니다.
*
* @param response Response object 에서 받은 Response Object 입니다.
* @param requestArgs fetch 함수의 인자들입니다.
* @param fetch {@link FetchHelperDefaultOptions['fetch']} 에서 제공한 `fetch` 입니다.
*
* @public
*/
response?: (response: Response, requestArgs: FetchArgs, fetch: NonNullable<FetchHelperDefaultOptions['fetch']>) => Promise<Response>;
};
}
/**
* @category Utils/Fetch
*
* 고차 함수로 fetch를 확장하거나, interceptor, baseUrl, headers 을 옵션으로 넣어 사용할 수 있습니다.
*
* @param defaultOptions - fetchHelper 함수의 옵션입니다.
*
* @example
*
* ```ts
* export const fetchHelperInterceptors: FetchHelper = (args) =>
* fetchHelper({
* ...args,
* interceptors: {
* request: requestInterceptor,
* response: responseInterceptor,
* },
* })
*
*
* import { fetchHelperInterceptors } from './fetch-interceptors'
*
* export const fetchExtended = fetchHelperInterceptors({
* baseUrl: https://jsonplaceholder.typicode.com
* })
*
* export default fetchExtended
*
* fetchExtended('/todos/1')
*
*
* ```
*/
declare const fetchHelper: (defaultOptions?: FetchHelperDefaultOptions) => (input: string | URL | Request, init?: RequestInit | undefined) => Promise<Response>;
export { type AssertItemOf, type AsyncFn, type AsyncFnReturn, type ByteUnit, type CreateS3UploadFlowConfig, type CreateS3UploadFlowReturn, type DataOrFn$1 as DataOrFn, type DataOrSetterFn, type DeepKeyOf, type DeepMutable, type DeepNonNullAble, type DeepNullAble, type DeepOmitReadOnly, type DeepPartial, type DeepValueOf, type FetchArgs, type FetchHelperDefaultOptions, type FetchHelperType, type FlatObjectParams, type Fn, type IfEquals, type Indices, InvalidTokenError, type ItemOf, type JwtDecodeOptions, type JwtHeader, type JwtPayload, Keep_F, Maybe_F, type MockedFn, type Mutable, type NonNullableProps, type NullAble, type Obj, type ObjSchemaByKey, type ObjSelector, type ObjSelectorMap, type ObjSelectorMapResult, type OmitReadOnly, type Parameter, type ReadonlyKeysOf, type RecursiveObj, type RelayParams, type RetryFnParams, type ValueOf, add, arrayToMap, arrayToRecord, assertItemOf, awaited, byteFrom, byteFromTo, byteTo, collect, createObjBySelector, createS3UploadFlow, delay, devide, effect, fetchHelper, flatObject, get, getDecimalPlaces, isEvery, isNotNullish, isNullish, isOverSize, jwtDecode, keep, log, maybe, multiply, not, or, paginate, pass, prefix, relay, removeEmptyObject, removeStr, retryReqeustManager, runIfFn, subtract, suffix, update, updateObj, volumeUpObject };