@gmana/utils
Version:
TypeScript utility functions with Tailwind CSS helpers and common JavaScript utilities
558 lines • 18.9 kB
TypeScript
//#region src/lib/absolute-url.d.ts
/**
* Creates an absolute URL by combining a base URL with a relative path.
*
* @param path - The relative path to append to the base URL. Can be null, undefined, or empty.
* @param options - Optional configuration for URL generation.
* @returns The absolute URL string.
*
* @example
* ```typescript
* absoluteUrl("/api/users") // "https://example.com/api/users"
* absoluteUrl("api/users") // "https://example.com/api/users"
* absoluteUrl("") // "https://example.com"
* absoluteUrl(null) // "https://example.com"
* absoluteUrl("/api/users", { query: { id: "123" } }) // "https://example.com/api/users?id=123"
* absoluteUrl("/api/users", { fragment: "section1" }) // "https://example.com/api/users#section1"
* ```
*/
declare function absoluteUrl(path?: string | null, options?: {
query?: Record<string, string | number | boolean | null | undefined>;
fragment?: string;
baseUrl?: string;
}): string;
/**
* Validates if a string is a valid URL.
*
* @param url - The URL string to validate.
* @returns True if the URL is valid, false otherwise.
*
* @example
* ```typescript
* isValidUrl("https://example.com") // true
* isValidUrl("not-a-url") // false
* ```
*/
declare function isValidUrl(url: string): boolean;
/**
* Joins multiple URL path segments together.
*
* @param segments - Array of path segments to join.
* @returns The joined path string.
*
* @example
* ```typescript
* joinPaths(["api", "users", "123"]) // "/api/users/123"
* joinPaths(["", "api", "users"]) // "/api/users"
* ```
*/
declare function joinPaths(segments: (string | null | undefined)[]): string;
//#endregion
//#region src/lib/array-utils.d.ts
/**
* Splits an array into chunks of specified size
*/
declare const chunk: <T>(array: T[], size: number) => T[][];
/**
* Returns unique elements from an array
*/
declare const unique: <T>(array: T[]) => T[];
/**
* Returns unique elements based on a key function
*/
declare const uniqueBy: <T, K>(array: T[], keyFn: (item: T) => K) => T[];
/**
* Groups array elements by a key function
*/
declare const groupBy: <T, K extends string | number | symbol>(array: T[], key: (item: T) => K) => Record<K, T[]>;
/**
* Flattens a nested array by one level
*/
declare const flattenArray: <T>(array: (T | T[])[]) => T[];
/**
* Deeply flattens a nested array
*/
declare const flattenDeepArray: <T>(array: (T | (T | T[])[])[]) => T[];
/**
* Returns the intersection of two arrays
*/
declare const intersection: <T>(array1: T[], array2: T[]) => T[];
/**
* Returns the difference between two arrays (items in first but not second)
*/
declare const difference: <T>(array1: T[], array2: T[]) => T[];
/**
* Returns the symmetric difference between two arrays
*/
declare const symmetricDifference: <T>(array1: T[], array2: T[]) => T[];
/**
* Partitions an array into two arrays based on a predicate
*/
declare const partition: <T>(array: T[], predicate: (item: T, index: number) => boolean) => [T[], T[]];
/**
* Removes falsy values from an array
*/
declare const compact: <T>(array: (T | null | undefined | false | 0 | "")[]) => T[];
/**
* Takes n elements from the beginning of an array
*/
declare const take: <T>(array: T[], n: number) => T[];
/**
* Takes elements from the end of an array
*/
declare const takeRight: <T>(array: T[], n: number) => T[];
/**
* Drops n elements from the beginning of an array
*/
declare const drop: <T>(array: T[], n: number) => T[];
/**
* Drops elements from the end of an array
*/
declare const dropRight: <T>(array: T[], n: number) => T[];
/**
* Shuffles an array using Fisher-Yates algorithm
*/
declare const shuffle: <T>(array: T[]) => T[];
/**
* Returns a random sample of n elements from an array
*/
declare const sample: <T>(array: T[], n?: number) => T[];
/**
* Sorts an array by multiple criteria
*/
declare const sortBy: <T>(array: T[], ...selectors: ((item: T) => unknown)[]) => T[];
/**
* Creates an array of arrays, grouping consecutive elements by a key function
*/
declare const groupConsecutive: <T, K>(array: T[], keyFn: (item: T) => K) => T[][];
/**
* Finds the maximum element in an array based on a selector function
*/
declare const maxBy: <T>(array: T[], selector: (item: T) => number) => T | undefined;
/**
* Finds the minimum element in an array based on a selector function
*/
declare const minBy: <T>(array: T[], selector: (item: T) => number) => T | undefined;
/**
* Calculates the sum of array elements based on a selector function
*/
declare const sumBy: <T>(array: T[], selector: (item: T) => number) => number;
/**
* Calculates the average of array elements based on a selector function
*/
declare const meanBy: <T>(array: T[], selector: (item: T) => number) => number;
/**
* Counts occurrences of each element in an array
*/
declare const countBy: <T, K extends string | number | symbol>(array: T[], keyFn: (item: T) => K) => Record<K, number>;
/**
* Zips multiple arrays together
*/
declare const zip: <T extends readonly unknown[][]>(...arrays: T) => Array<{ [K in keyof T]: T[K] extends readonly (infer U)[] ? U : never }>;
//#endregion
//#region src/lib/clsx.d.ts
type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | boolean;
interface ClassDictionary {
[key: string]: boolean | undefined | null;
}
type ClassArray = Array<ClassValue>;
/**
* Joins classNames together.
*
* Accepts a variadic number of arguments. Each argument can be a string,
* number, array, or object mapping strings to boolean values.
*
* Returns a single string of class names.
*/
declare function clsx(...args: ClassValue[]): string;
//#endregion
//#region src/lib/cn.d.ts
declare const cn: (...inputs: ClassValue[]) => string;
//#endregion
//#region src/lib/compact-object.d.ts
type JSONPrimitive = string | number | boolean | null | undefined;
interface JSONObject {
[key: string]: JSONValue;
}
type JSONArray = Array<JSONValue>;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
/**
* Configuration options for the compactObject function
*/
interface CompactOptions {
/** Whether to compact arrays recursively (default: true) */
compactArrays?: boolean;
/** Whether to remove empty arrays (default: false) */
removeEmptyArrays?: boolean;
/** Custom predicate to determine if a value should be removed */
isEmpty?: (value: unknown) => boolean;
}
/**
* Recursively removes empty values from an object.
* By default, removes: `''`, `undefined`, `null`, and empty objects.
*
* @param obj - The object to compact
* @param options - Configuration options for compacting behavior
* @returns A new object with empty values removed
*
* @example
* ```ts
* const input = {
* name: "John",
* email: "",
* address: {
* street: "123 Main St",
* city: null,
* nested: {}
* },
* tags: ["tag1", "", "tag2"]
* }
*
* const result = compactObject(input)
* // Result: { name: "John", address: { street: "123 Main St" }, tags: ["tag1", "tag2"] }
* ```
*/
declare function compactObject<T extends Record<string, unknown>>(obj: T, options?: CompactOptions): Partial<T>;
/**
* A more restrictive version that only works with JSON-serializable objects
* and provides better type safety for JSON use cases.
*/
declare function compactJSONObject<T extends JSONObject>(obj: T, options?: CompactOptions): Partial<T>;
//#endregion
//#region src/lib/convert-case.d.ts
/**
* A union of supported string case types.
*/
type CaseType = "lowercase" | "uppercase" | "sentence" | "title" | "snake" | "kebab" | "camel" | "pascal" | "dot" | "constant";
/**
* Extracts words from a string, intelligently handling various formats like
* camelCase, PascalCase, snake_case, and kebab-case.
* @param input The string to process.
* @returns An array of words.
*/
declare function extractWords(input: string): string[];
/**
* Converts a string into a specified case format.
* @param input The string to convert.
* @param caseType The target case format.
* @returns The converted string.
*/
declare function convertCase(input: string, caseType: CaseType): string;
/**
* Utility function to convert strings to common case formats with shorter names.
*/
declare const toCase: {
lower: (input: string) => string;
upper: (input: string) => string;
sentence: (input: string) => string;
title: (input: string) => string;
snake: (input: string) => string;
kebab: (input: string) => string;
camel: (input: string) => string;
pascal: (input: string) => string;
dot: (input: string) => string;
constant: (input: string) => string;
};
//#endregion
//#region src/lib/flatten.d.ts
/**
* Flattens a nested object or array into a single-level object.
* @param obj The object or array to flatten.
* @param separator The string to use between nested keys.
* @returns A flattened object.
*/
declare const flatten: (obj: Record<string, unknown>, separator?: string) => Record<string, unknown>;
//#endregion
//#region src/lib/is.d.ts
declare const isClient: boolean;
declare const isServer: boolean;
/**
* Checks if the given value is an array.
*/
declare const isArray: (input: unknown) => input is any[];
/**
* Checks if the given value is a boolean primitive.
*/
declare const isBoolean: (value: unknown) => value is boolean;
/**
* Checks if the current environment is a development environment.
* Returns true if NODE_ENV is 'development' or 'test'.
*/
declare const isDev: boolean;
/**
* Checks if the given value is empty.
*/
declare const isEmpty: (input: unknown) => boolean;
/**
* Checks if the given value is a function.
*/
declare const isFunction: (value: unknown) => value is (...args: unknown[]) => unknown;
/**
* Checks if navigator is available.
*/
declare const isNavigator: boolean;
/**
* Checks if the given value is a number.
*/
declare const isNumber: (value: unknown) => boolean;
/**
* Checks if the given value is an object.
* Returns true if the value is not null and is of type 'object'.
*/
declare const isObject: (value: unknown) => value is object;
/**
* Checks if the given value is a string primitive.
*/
declare const isString: (value: unknown) => value is string;
/**
* Checks if the given value is a symbol.
*/
declare function isSymbol(value: unknown): boolean;
/**
* Is token expired?
*
* @param token - JWT token to check
* @param offsetSeconds - Optional offset in seconds to consider token expired earlier
* @returns true if token is expired or invalid, false if valid
*/
declare function isTokenExpired(token: string, offsetSeconds?: number): boolean;
/**
* Checks if the given value is undefined.
*
* @param value - The value to check.
* @returns Whether the value is undefined.
*/
declare const isUndef: (value: unknown) => value is undefined;
/**
* Checks if the given url is valid
* @param url - The url to check
* @returns True if url is valid, false otherwise
*/
declare function isUrl(url: string | URL): boolean;
/**
* Utility type for component validation results
*/
type ComponentValidationResult = {
valid: boolean;
errors: string[];
};
/**
* Comprehensive validation for component names
* @param name - The component name to validate
* @param options - Validation options
* @returns Validation result with detailed feedback
* @example
* isValidComponentName("my-component") // { valid: true, errors: [] }
* isValidComponentName("") // { valid: false, errors: ["Name cannot be empty"] }
* isValidComponentName("My-Component") // { valid: false, errors: ["Name must be lowercase"] }
*/
declare function isValidComponentName(name: string, options?: {
allowEmpty?: boolean;
minLength?: number;
maxLength?: number;
}): ComponentValidationResult;
/**
* Checks if the given string is valid JSON.
*
* @param str - The string to check.
* @returns True if the string is valid JSON, false otherwise.
*/
declare function isValidJsonString(str: string): boolean;
//#endregion
//#region src/lib/number.d.ts
declare const toASCII: (s: string) => string;
declare const toKhmer: (s: string) => string;
/**
* @description
* Converts a number to its word representation in English.
* @example
// Example usage:
const doubleNumber = 1234567.99
//result: One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven Point Eight Nine
const wordRepresentation = convertToWord(doubleNumber)
console.log(`${doubleNumber} in words: ${wordRepresentation}`)
*/
declare function numberToWord(n: number): string;
/**
* Converts a number to a string representation in Khmer words.
*
* @param value - The number to convert to words
* @param sep - Separator between number groups, default ' '
* @param del - Decimal point separator, default ' ក្បៀស '
* @returns String representation of the number in Khmer words
* @example
console.log(numberToWordKm(1234567.89))
// result: មួយលាន ពីរសែន បីម៉ឺន បួនពាន់ ប្រាំរយ ហុកសិបប្រាំពីរ ក្បៀស ប្រាំបី ប្រាំបួន
*/
declare function numberToWordKm(value: number, sep?: string, del?: string): string;
/**
* Formats a number with standard suffixes (K, M, B, T, etc.).
*
* @param value - The number to format. If null, undefined, or 0, returns "0"
* @param decimalPlaces - Number of decimal places to include. Defaults to 1
* @returns The formatted number string with appropriate suffix
*
* @example
* formatNumber(1234) // "1.2K"
* formatNumber(1234567, 2) // "1.23M"
* formatNumber(0) // "0"
* formatNumber(-1500) // "-1.5K"
*/
declare function formatNumber(value?: number | null, decimalPlaces?: number): string;
declare const formatCurrency: ({
amount,
currencyCode,
minFractionDigits,
maxFractionDigits,
locale
}: {
amount: number;
currencyCode: string;
minFractionDigits?: number;
maxFractionDigits?: number;
locale?: string;
}) => string;
//#endregion
//#region src/lib/v-card.d.ts
/**
* VCard Generator - A utility for creating vCard 4.0 format contact cards
* Supports social media, messaging platforms, and comprehensive contact information
*/
interface ISocialMedia {
facebook?: string;
twitter?: string;
linkedin?: string;
instagram?: string;
youtube?: string;
github?: string;
}
interface IMessagingPlatforms {
telegram?: string;
whatsapp?: string;
messenger?: string;
skype?: string;
discord?: string;
}
interface IAddress {
type?: "home" | "work" | "other";
street?: string;
city?: string;
state?: string;
postalCode?: string;
country?: string;
}
interface VCardContact {
firstName?: string;
lastName?: string;
nickname?: string;
organization?: string;
title?: string;
department?: string;
email?: string | string[];
phone?: string | string[];
mobile?: string | string[];
fax?: string | string[];
address?: IAddress[];
website?: string;
birthday?: Date;
photo?: string;
social?: ISocialMedia;
messaging?: IMessagingPlatforms;
categories?: string[];
note?: string;
}
/**
* Utility class for generating vCard 4.0 format contact cards
*/
declare class VCardGenerator {
private static readonly VCARD_VERSION;
private static readonly SOCIAL_PLATFORMS;
private static readonly MESSAGING_PLATFORMS;
/**
* Escapes special characters for vCard format
* @param value - String to escape
* @returns Escaped string safe for vCard format
*/
private static escapeVCard;
/**
* Formats a date to vCard BDAY format (YYYYMMDD)
* @param date - Date to format
* @returns Formatted date string
*/
private static formatDate;
/**
* Formats email addresses for vCard
* @param emails - Single email or array of emails
* @returns Array of formatted email lines
*/
private static formatEmails;
/**
* Formats address information for vCard
* @param address - Address object
* @returns Formatted address line
*/
private static formatAddress;
/**
* Formats social media profiles for vCard
* @param social - Social media object
* @returns Array of formatted social media lines
*/
private static formatSocialMedia;
/**
* Formats messaging platform information for vCard
* @param messaging - Messaging platforms object
* @returns Array of formatted messaging lines
*/
private static formatMessaging;
/**
* Formats phone numbers for vCard
* @param values - Phone number(s)
* @param type - Phone type (WORK,VOICE | CELL,VOICE | FAX)
* @returns Array of formatted phone lines
*/
private static formatPhones;
/**
* Formats photo data for vCard
* @param photo - Photo URL or base64 data
* @returns Formatted photo line or null
*/
private static formatPhoto;
/**
* Validates contact data before generating vCard
* @param contact - Contact object to validate
* @throws Error if contact data is invalid
*/
private static validateContact;
/**
* Generates a vCard 4.0 string from contact information
* @param contact - Contact information object
* @returns vCard formatted string
* @throws Error if contact data is invalid
*/
static generate(contact: VCardContact): string;
/**
* Creates a downloadable blob for the vCard
* @param contact - Contact information
* @returns Blob object for download
*/
static createDownloadBlob(contact: VCardContact): Blob;
}
//#endregion
//#region src/lib/get-initial-letter.d.ts
/**
* Generates a one or two-letter initial string from a full name.
* It takes the first letter of the first two name parts.
* This function correctly handles diacritics, extra whitespace, and empty or invalid inputs.
*
* @example
* getInitialLetter("John Doe") // "JD"
* getInitialLetter(" Beyoncé Knowles-Carter") // "BK"
* getInitialLetter("Cher") // "C"
* getInitialLetter(null) // ""
*
* @param fullName The full name to process. Can be a string, null, or undefined.
* @returns The uppercase initials (1 or 2 characters), or an empty string if the input is invalid.
*/
declare function getInitialLetter(fullName?: string | null): string;
//#endregion
export { CaseType, ClassValue, ComponentValidationResult, IAddress, IMessagingPlatforms, ISocialMedia, VCardContact, VCardGenerator, absoluteUrl, chunk, clsx, cn, compact, compactJSONObject, compactObject, convertCase, countBy, difference, drop, dropRight, extractWords, flatten, flattenArray, flattenDeepArray, formatCurrency, formatNumber, getInitialLetter, groupBy, groupConsecutive, intersection, isArray, isBoolean, isClient, isDev, isEmpty, isFunction, isNavigator, isNumber, isObject, isServer, isString, isSymbol, isTokenExpired, isUndef, isUrl, isValidComponentName, isValidJsonString, isValidUrl, joinPaths, maxBy, meanBy, minBy, numberToWord, numberToWordKm, partition, sample, shuffle, sortBy, sumBy, symmetricDifference, take, takeRight, toASCII, toCase, toKhmer, unique, uniqueBy, zip };