UNPKG

@utilify/core

Version:

Modern, strongly typed, and safe utility function library for JavaScript and TypeScript. Includes type checking, manipulation of arrays, objects, strings, dates, colors, numbers, regular expressions, and more. Compatible with Browser, Node.js, Deno, and B

572 lines (325 loc) 22.1 kB
declare function adjust<T>(array: T[], index: number, fn: (value: T) => T): T[]; declare function after(string: string, index: number): string; declare function after<T>(array: T[], index: number): T[]; declare function aperture<T>(array: T[], size?: number): T[][]; declare function append<T>(array: T[], value: T): T[]; declare function arrayToObject<T, K extends PropertyKey>(array: T[], keyFn?: (item: T, index: number, array: T[]) => K, valueFn?: (item: T, index: number, array: T[]) => T): Record<K, any>; declare function before(string: string, index: number): string; declare function before<T>(array: T[], index: number): T[]; declare function chunk(string: string, size: number): string; declare function chunk<T>(array: T[], size: number): T[][]; declare function collectBy<T, K extends PropertyKey>(array: T[], keySelector: (value: T, index: number) => K): T[][]; declare function compact<T>(array: T[]): T[]; declare function count<T>(array: T[], predicate: (item: T) => boolean): number; declare function cycle<T>(array: T[]): () => T | undefined; declare function difference<T>(array1: T[], array2: T[]): T[]; declare function first(string: string, count?: number): string; declare function first<T>(array: T[], count?: number): T[]; declare function flatMap<T, U>(array: T[], fn: (value: T, index: number, array: T[]) => U | U[]): U[]; declare function flat<T>(array: T[], depth?: number): FlatArray<T[], number>[]; declare function groupBy<T, K extends PropertyKey>(array: T[], keySelector?: (value: T, index: number) => K): Record<K, T[]>; declare function includes<T>(array: T[], value: T): boolean; declare function isIterable(value: any): value is Iterable<any>; declare function last(string: string, count?: number): string; declare function last<T>(array: T[], count?: number): T[]; declare function reject<T>(array: T[], fn: (value: T, index?: number, array?: T[]) => boolean): T[]; declare function repeat<T>(value: T, count: number): T[]; declare function repeat(value: string, count: number): string; declare function rotate<T>(array: T[], offset: number): T[]; declare function sample<T>(array: T[]): T | undefined; declare function shuffle<T>(array: T[]): T[]; declare function swap<T>(array: T[], fromIndex: number, toIndex: number): T[]; declare function union<T>(...arrays: T[][]): T[]; declare function unique<T>(array: T[]): T[]; declare function unzip<T>(zip: T[][]): T[][]; declare function zip<T>(...arrays: T[][]): T[][]; declare function exitFullscreen(): Promise<void>; declare function getLanguage(): string | undefined; declare function getTheme(): 'dark' | 'light'; declare function isCookieEnabled(): boolean | undefined; declare function isFullscreenEnabled(): boolean; declare function isOnline(): boolean | undefined; declare function isShareable(data?: ShareData): boolean; declare function isTabActive(): boolean; declare function isTouchDevice(): boolean | undefined; declare function on<T extends Window | Document | HTMLElement | EventTarget>(target: T, event: keyof WindowEventMap | keyof DocumentEventMap | keyof HTMLElementEventMap, listener: (this: T, ev: Event) => any, options?: boolean | AddEventListenerOptions): () => void; declare function onOffline(listener: () => void): () => void; declare function onOnline(listener: () => void): () => void; declare function onVisibilityChange(listener: (visibilityState: Document['visibilityState']) => void): () => void; declare function requestFullscreen(element: Element): Promise<void>; declare function scrollToElement(element: HTMLElement, options?: boolean): void; declare function scrollToElement(element: HTMLElement, options?: ScrollIntoViewOptions): void; declare function scrollToTop(behavior?: ScrollBehavior): void; declare function share(data: ShareData): Promise<void>; type ParsedColor = { model: "rgb" | "hsl"; values: [number, number, number]; alpha?: number; } | null; declare function parseColor(color: string): ParsedColor; declare function hexToHsl(hex: string): string; declare function hexToRgb(hex: string): string; declare function hslToHex(hsl: string): string; declare function hslToRgb(hsl: string): string; declare function isHexColor(hex: string): boolean; declare function isHslColor(hsl: string): boolean; declare function isRgbColor(rgb: string): boolean; declare function rgbToHex(rgb: string): string; declare function rgbToHsl(rgb: string): string; type Format = "hex" | "rgb" | "hsl"; declare function randomColor(format: Format | undefined, alpha: boolean): string; declare function base64Decode(input: string, urlSafe?: boolean): Uint8Array; declare function base64Encode(input: Uint8Array | ArrayBuffer, urlSafe?: boolean): string; declare function djb2(str: string): number; declare function generateNonce(length?: number): Uint8Array; declare function generateUUID(): string; declare function hexDecode(hex: string): Uint8Array; declare function hexEncode(data: ArrayBuffer | Uint8Array): string; declare function isArrayBuffer(input: unknown): input is ArrayBuffer; declare function isBase64(value: string): boolean; declare function isBase64URL(value: string): boolean; type HashAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'; declare function isHash(hash: string, algorithm?: HashAlgorithm): boolean; declare function isHex(value: string): boolean; declare function isUint8Array(input: unknown): input is Uint8Array; declare function isUUID(value: string): boolean; declare function utf8Decode(data: ArrayBuffer | Uint8Array): string; declare function utf8Encode(input: string): Uint8Array; declare function adjustDate(date: Date, adjustment: Partial<{ years: number; months: number; days: number; hours: number; minutes: number; seconds: number; milliseconds: number; }>): Date; declare function adjustTimezone(date: Date, targetTimezone: number): Date; type DateFormat$1 = "timestamp" | "string" | "utc" | "iso"; declare function convertDateTo(date: Date, format?: DateFormat$1): string | number; type TimeUnit$1 = "milliseconds" | "seconds" | "minutes" | "hours" | "days" | "years"; declare function convertTimeUnit(time: number, from: TimeUnit$1, to: TimeUnit$1): number; type TimeUnit = "milliseconds" | "seconds" | "minutes" | "hours" | "days" | "years"; declare function elapsedTime(from: Date, to?: Date, unit?: TimeUnit): number; type DateFormat = "DMY" | "MDY" | "YMD"; declare function formatDate(date: Date, format: DateFormat, separator?: string): string; declare function formatDuration(ms: number, format?: string, autoHour?: boolean): string; declare function formatTime(date: Date, format?: string): string; declare function isBetween(date: Date, start: Date, end: Date, inclusive?: boolean): boolean; declare function isLeapYear(year: string): boolean; declare function isLeapYear(year: number): boolean; declare function isSameDay(date1: Date, date2: Date): boolean; declare function isToday(date: Date): boolean; declare function isTomorrow(date: Date): boolean; declare function isValidDate(value: Date): boolean; declare function isValidDateString(date: string): boolean; declare function isWeekday(date: Date): boolean; declare function isWeekend(date: Date): boolean; declare function isYesterday(date: Date): boolean; declare function parseDate(date: Date): Date; declare function parseDate(date: string): Date; declare function parseDate(date: number): Date; declare function stripTime(date: Date): Date; declare function toDate(value: Date): Date; declare function toDate(value: string): Date; declare function toDate(value: number): Date; declare function equalsEnv(key: string, expected: string | string[]): boolean; declare function getEnv(key: string, fallback?: string): string | undefined; declare function getOS(): string | undefined; declare function getRuntime(): 'Browser' | 'Node' | 'Deno' | 'Bun' | 'Unknown'; declare function hasEnv(key: string): boolean; declare function isBrowser(): boolean; declare function isBun(): boolean; declare function isDedicatedWorker(): boolean; declare function isDeno(): boolean; declare function isDev(): boolean; declare function isMobile(): boolean | undefined; declare function isNode(): boolean; declare function isProd(): boolean; declare function isServer(): boolean; declare function isServiceWorker(): boolean; declare function isSharedWorker(): boolean; declare function isTest(): boolean; declare function isWebWorker(): boolean; declare function requireEnv(key: string): string; declare function customError(name: string): new (message?: string, options?: ErrorOptions) => Error; declare function isAggregateError(value: any): value is AggregateError; declare function isDOMException(value: any): value is DOMException; declare function isError(value: any): value is { name: string; message: string; stack?: string; }; declare function isEvalError(value: any): value is EvalError; declare function isRangeError(value: any): value is RangeError; declare function isReferenceError(value: any): value is ReferenceError; declare function isSyntaxError(value: any): value is SyntaxError; declare function isTypeError(value: any): value is TypeError; declare function isURIError(value: any): value is URIError; declare function compose<T>(...callbacks: ((value: T) => T)[]): (value: T) => T; declare function identity<T>(value: T): T; declare function memo<T extends (...args: any[]) => any>(callback: T, { cacheTimeout, serializer }?: { cacheTimeout?: number; serializer?: (args: Parameters<T>) => string; }): (...args: Parameters<T>) => ReturnType<T>; declare function noop(): void; declare function not<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => boolean; declare function once<T extends (...args: any[]) => any>(callback: T): (...args: Parameters<T>) => ReturnType<T>; type DropFirst<T extends any[]> = T extends [any, ...infer R] ? R : never; declare function partialLeft<Args extends any[], R, P extends Partial<Args>>(callback: (...args: Args) => R, ...partial: P): (...args: DropFirst<Args> extends P ? [] : DropFirst<Args>) => R; type DropLast<T extends any[], N extends any[]> = T extends [...infer R, ...N] ? R : never; declare function partialRight<Args extends any[], R, P extends Partial<Args>>(callback: (...args: Args) => R | Promise<R>, ...partial: P): (...args: DropLast<Args, P>) => R | Promise<R>; declare function pipe<T>(...callbacks: ((value: T) => T)[]): (value: T) => T; declare function times<T>(callback: (index: number) => T, count: number): T[]; declare function when<T extends (...args: any) => any>(predicate: (...args: any) => boolean, action: T): (...args: Parameters<T>) => ReturnType<T> | undefined; declare function add(...values: number[]): number; declare function clamp(value: number, min: number, max: number): number; declare function divide(dividend: number, divisor: number): number; declare function factorial(value: number): number; declare function fibonacci(num: number): number; declare function frequency(arr: any[]): Record<PropertyKey, number>; declare function lerp(start: number, end: number, amount: number): number; declare function mean(values: number[]): number; declare function median(arr: number[]): number; declare function mod(dividend: number, divisor: number): number; declare function mode(arr: number[]): number[]; declare function multiply(...values: number[]): number; declare function pow(base: number, exponent: number): number; declare function random(min?: number, max?: number): number; declare function roundTo(value: number, precision?: number): number; declare function std(arr: number[]): number; declare function subtract(...values: number[]): number; declare function variance(arr: number[]): number; declare function divisors(value: number): number[]; declare function inRange(value: number, min: number, max: number): boolean; declare function isEven(value: number): boolean; declare function isFinite(value: number): boolean; declare function isFloat(value: number): boolean; declare function isInfinity(value: number): boolean; declare function isInteger(value: number): boolean; declare function isNaN(value: any): value is number; declare function isNegative(value: number): boolean; declare function isOdd(value: number): boolean; declare function isPositive(value: number): boolean; declare function isPrime(value: number): boolean; declare function range(start: number, end: number, step?: number): number[]; declare function sumOfDigits(value: number): number; declare function clone<T>(value: T): T; declare function flattenObj(obj: any): Record<string, any>; declare function freeze(obj: Record<PropertyKey, any>): Record<PropertyKey, any>; declare function get<T extends Record<PropertyKey, any>>(obj: T, path: string | string[], defaultValue?: any): T; declare function has<T extends Record<PropertyKey, any>>(obj: T, path: string | string[]): boolean; declare function isEqual(value1: any, value2: any): boolean; declare function isFrozen(obj: any): boolean; declare function isNotNullObject(value: any): boolean; declare function isPlainObject(value: any): value is Record<PropertyKey, any>; declare function isSealed(obj: any): boolean; declare function merge(target: any, source: any): any; declare function omit<T extends Record<PropertyKey, any>, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>; declare function pick<T extends Record<PropertyKey, any>, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>; declare function seal(obj: Record<PropertyKey, any>): Record<PropertyKey, any>; declare function set<T extends Record<PropertyKey, any>>(obj: T, path: string | string[], value: any): T; declare function unflattenObj(obj: Record<string, any>): any; type BackoffMode = 'fixed' | 'linear' | 'exponential'; type JitterMode = 'none' | 'full' | 'equal' | 'decorrelated'; interface BackoffOptions { backoffMode?: BackoffMode; initialDelay?: number; jitterMode?: JitterMode; maxDelay?: number; maxAttempts?: number; onRetry?: (attempt: number, currentDelay: number) => void; } declare function backoff<T>(action: () => Promise<T>, { initialDelay, backoffMode, jitterMode, maxAttempts, maxDelay, onRetry, }?: BackoffOptions): Promise<T>; declare function benchmark(callback: () => void, iterations: number): Promise<number>; declare function benchmark(callback: () => Promise<void>, iterations: number): Promise<number>; type DebounceOptions = { leading?: boolean; trailing?: boolean; maxWait?: number; }; declare function debounce<T extends (...args: any[]) => void>(callback: T, wait?: number, options?: DebounceOptions): ((...args: Parameters<T>) => void) & { cancel: () => void; flush: () => void; }; declare function defer(callback: () => void): void; declare function lock<T extends (...args: any[]) => Promise<any>>(callback: T, options?: { queue?: boolean; onLocked?: () => void | Promise<void>; onError?: (error: unknown) => void | Promise<void>; }): (...args: Parameters<T>) => Promise<ReturnType<T> | void>; declare function parallel(...callbacks: (() => Promise<any>)[]): Promise<any[]>; declare function rate<T extends (...args: any[]) => any>(callback: T, limit: number, interval: number): (...args: Parameters<T>) => boolean; declare function retry<T>(callback: () => T, attempts: number): T; declare function sleep(timeout: number): Promise<void>; type ThrottleOptions = { leading?: boolean; trailing?: boolean; maxWait?: number; }; interface ThrottledFunction<T extends (...args: any[]) => void> { (...args: Parameters<T>): void; cancel(): void; flush(): void; } declare function throttle<T extends (...args: any[]) => void>(callback: T, wait: number, { leading, trailing, maxWait, }?: ThrottleOptions): ThrottledFunction<T>; declare function isAlpha(value: string): boolean; declare function isAlphanumeric(value: string): boolean; declare function isEmail(value: string): boolean; declare function isURL(value: string): boolean; declare function isCreditCard(value: string): boolean; declare function isSlug(value: string): boolean; declare function isIPV4(value: string): boolean; declare function isIPV6(value: string): boolean; declare function isJWT(value: string): boolean; declare function isFileExtension(fileName: string, extensions: string): boolean; declare function isFileExtension(fileName: string, extensions: string[]): boolean; declare function capitalize(str: string): string; declare function charCount(str: string, char: string): number; declare function escapeHtml(str: string): string; declare function interpolate(str: string, data: Record<PropertyKey, any>, pattern?: RegExp): string; declare function invertCase(str: string): string; declare function isLowerCase(str: string): boolean; declare function isUpperCase(str: string): boolean; declare function maskString(str: string, mask: string, maskStart: number, maskLength: number): string; declare function removeAccents(str: string): string; declare function slugify(str: string): string; declare function stripHtml(html: string): string; interface TemplateOptions { pattern?: RegExp; escape?: (value: string, key: string) => string; } declare function template(str: string, options: TemplateOptions): (data: Record<string, any>) => string; declare function toCamelCase(str: string): string; declare function toKebabCase(str: string): string; declare function toPascalCase(str: string): string; declare function toSnakeCase(str: string): string; declare function truncate(text: string, size: number): string; declare function wordCount(str: string): number; declare function getInstanceType(value: any): string | null; declare function getType(value: any): string; declare function isArray(value: any): value is any[]; declare function isAsyncFunction(value: any): value is (...args: any[]) => Promise<any>; declare function isAsyncGeneratorFunction(value: any): value is AsyncGeneratorFunction; declare function isBigint(value: any): value is bigint; declare function isBoolean(value: any): value is boolean; declare function isDate(value: any): value is Date; declare function isFalsy(value: any): boolean; declare function isFunction(value: any): value is Function; declare function isGeneratorFunction(value: any): value is GeneratorFunction; declare function isMap(value: any): value is Map<any, any>; declare function isNil(value: any): value is undefined | null; declare function isNull(value: any): value is null; declare function isNumber(value: any): value is number; declare function isObject(value: any): value is Record<PropertyKey, any>; declare function isPrimitive(value: any): value is undefined | null | boolean | number | bigint | string | symbol; declare function isPromise(value: any): value is Promise<any>; declare function isRegExp(value: any): value is RegExp; declare function isSet(value: any): value is Set<any>; declare function isString(value: any): value is string; declare function isSymbol(value: any): value is symbol; declare function isUndefined(value: any): value is undefined; declare function isWeakMap(value: any): value is WeakMap<object, any>; declare function isWeakSet(value: any): value is WeakSet<object>; declare function isWeakRef(value: any): value is WeakRef<object>; export { add, adjust, adjustDate, adjustTimezone, after, aperture, append, arrayToObject, backoff, base64Decode, base64Encode, before, benchmark, capitalize, charCount, chunk, clamp, clone, collectBy, compact, compose, convertDateTo, convertTimeUnit, count, customError, cycle, debounce, defer, difference, divide, divisors, djb2, elapsedTime, equalsEnv, escapeHtml, exitFullscreen, factorial, fibonacci, first, flat, flatMap, flattenObj, formatDate, formatDuration, formatTime, freeze, frequency, generateNonce, generateUUID, get, getEnv, getInstanceType, getLanguage, getOS, getRuntime, getTheme, getType, groupBy, has, hasEnv, hexDecode, hexEncode, hexToHsl, hexToRgb, hslToHex, hslToRgb, identity, inRange, includes, interpolate, invertCase, isAggregateError, isAlpha, isAlphanumeric, isArray, isArrayBuffer, isAsyncFunction, isAsyncGeneratorFunction, isBase64, isBase64URL, isBetween, isBigint, isBoolean, isBrowser, isBun, isCookieEnabled, isCreditCard, isDOMException, isDate, isDedicatedWorker, isDeno, isDev, isEmail, isEqual, isError, isEvalError, isEven, isFalsy, isFileExtension, isFinite, isFloat, isFrozen, isFullscreenEnabled, isFunction, isGeneratorFunction, isHash, isHex, isHexColor, isHslColor, isIPV4, isIPV6, isInfinity, isInteger, isIterable, isJWT, isLeapYear, isLowerCase, isMap, isMobile, isNaN, isNegative, isNil, isNode, isNotNullObject, isNull, isNumber, isObject, isOdd, isOnline, isPlainObject, isPositive, isPrime, isPrimitive, isProd, isPromise, isRangeError, isReferenceError, isRegExp, isRgbColor, isSameDay, isSealed, isServer, isServiceWorker, isSet, isShareable, isSharedWorker, isSlug, isString, isSymbol, isSyntaxError, isTabActive, isTest, isToday, isTomorrow, isTouchDevice, isTypeError, isURIError, isURL, isUUID, isUint8Array, isUndefined, isUpperCase, isValidDate, isValidDateString, isWeakMap, isWeakRef, isWeakSet, isWebWorker, isWeekday, isWeekend, isYesterday, last, lerp, lock, maskString, mean, median, memo, merge, mod, mode, multiply, noop, not, omit, on, onOffline, onOnline, onVisibilityChange, once, parallel, parseColor, parseDate, partialLeft, partialRight, pick, pipe, pow, random, randomColor, range, rate as rateLimit, reject, removeAccents, repeat, requestFullscreen, requireEnv, retry, rgbToHex, rgbToHsl, rotate, roundTo, sample, scrollToElement, scrollToTop, seal, set, share, shuffle, sleep, slugify, std, stripHtml, stripTime, subtract, sumOfDigits, swap, template, throttle, times, toCamelCase, toDate, toKebabCase, toPascalCase, toSnakeCase, truncate, unflattenObj, union, unique, unzip, utf8Decode, utf8Encode, variance, when, wordCount, zip };