@devlander/utils
Version:
Comprehensive JavaScript and TypeScript utilities for seamless development. Includes object manipulation, data validation, and more.
1,227 lines (1,125 loc) • 47.6 kB
TypeScript
declare function arrayToObject<T>(arr: T[]): {
[key: string]: T;
};
/**
* Breaks an array into smaller chunks of the specified size.
*
* ✅ Works in Node.js, React, and React Native.
*
* @example
* chunkArray([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
* chunkArray([1, 2, 3, 4], 3) // [[1, 2, 3], [4]]
* chunkArray([1, 2, 3], 1) // [[1], [2], [3]]
* chunkArray([], 2) // []
*
* @param array - The array to split into chunks
* @param size - The maximum size of each chunk
* @returns An array of arrays, each containing up to 'size' elements
*/
declare const chunkArray: <T>(array: T[], size: number) => T[][];
declare enum DeduplicateInputType {
STRING = "string",
OBJECT = "object",
ARRAY = "array",
NUMBER = "number",
MATRIX = "matrix"
}
/**
* Deduplicates elements from various input types, including strings, arrays, objects,
* numbers, and matrices, based on the specified type. This replaces the removeDuplicatesFromString that was used in previous projects.
*
* @param input - The input from which to remove duplicates. Supported types are `string`,
* `Record<string, unknown>`, `unknown[]`, or `number`.
* @param inputType - Specifies the type of the input to control the deduplication strategy.
* Accepts either `DeduplicateInputType` enum values or their string literals (e.g., "string").
* If not provided, the function will auto-detect the input type.
* @returns The input with duplicates removed, formatted according to the specified input type:
* - `STRING` - Returns a string with duplicate characters removed.
* - `ARRAY` - Returns an array with duplicate elements removed.
* - `OBJECT` - Returns an object with unique key-value pairs.
* - `NUMBER` - Returns a number with duplicate digits removed.
* - `MATRIX` - For a 2D array, removes duplicate elements within each sub-array (row).
*
* @throws Will throw an error if the input type is unsupported or if the input format
* does not match the specified `inputType`.
*/
declare const deduplicate: (input: string | Record<string, unknown> | unknown[] | number, inputType?: DeduplicateInputType | keyof typeof DeduplicateInputType) => string | Record<string, unknown> | number | unknown[];
declare const defaultStopWords: string[];
/**
* Generic interface representing an item with an identifier and search fields.
*
* @template IdType - Type of the item's identifier (string or number).
* @template ItemType - Type of each item in the dataItems array.
*/
type SearchableItem<ItemType, IdType extends string | number> = ItemType & {
[key: string]: any;
_id?: IdType;
};
/**
* Filters and suggests objects from an array based on a description and specified fields.
*
* @template ItemType - Type of the items to be searched.
* @template IdType - Type of the identifier for each item (string or number).
* @param searchText - The text to search within items.
* @param dataItems - The array of objects to search through.
* @param excludedIds - An array of IDs or a single ID to exclude from search results.
* @param fieldsToSearch - The keys within each item to search against. Defaults to `["name"]`.
* @param idKey - The key representing the unique identifier in each item. Defaults to `_id`.
* @param stopWords - A list of words to exclude from the search. Defaults to `defaultStopWords`.
* @returns A filtered array of objects matching the search criteria.
*
* @example
* // Basic usage with custom data shape
* interface Product {
* id: string;
* name: string;
* description: string;
* }
*
* const products: Product[] = [
* { id: "1", name: "Apple", description: "A fresh apple" },
* { id: "2", name: "Banana", description: "Yellow banana" },
* ];
*
* const results = filterAndSuggestItems<Product, string>(
* "apple",
* products,
* [], // No excluded IDs
* ["name", "description"], // Fields to search within
* "id" // ID key
* );
* console.log(results); // Logs items containing "apple"
*/
declare function filterAndSuggestItems<ItemType, IdType extends string | number = string>(searchText?: string, dataItems?: SearchableItem<ItemType, IdType>[], excludedIds?: IdType[] | IdType, fieldsToSearch?: string[], idKey?: string, // Default to '_id' to match Product interface
stopWords?: string[]): SearchableItem<ItemType, IdType>[];
/**
* Flattens a nested array by one level.
*
* @param array - The array to flatten.
* @returns A flattened array (one level deep).
*
* @example
* ```typescript
* flattenArray([1, [2, 3], [4, 5]]); // Returns: [1, 2, 3, 4, 5]
* flattenArray([[1, 2], [3, 4], [5, 6]]); // Returns: [1, 2, 3, 4, 5, 6]
* flattenArray([1, 2, 3]); // Returns: [1, 2, 3]
* flattenArray([1, [2, [3, 4]]]); // Returns: [1, 2, [3, 4]]
* ```
*/
declare const flattenArray: <T>(array: T[]) => T[];
declare function forEach<T>(obj: T | T[] | null | undefined, fn: (value: T[keyof T] | unknown, key: keyof T | string | number, obj: T | T[]) => void, { allOwnKeys }?: {
allOwnKeys?: boolean;
}): void;
type IterableObject<T> = {
[Symbol.iterator]: () => IterableIterator<[string, T]>;
};
type ForEachEntryCallback<T> = (key: string, value: T) => void;
declare const forEachEntry: <T>(obj: IterableObject<T>, fn: ForEachEntryCallback<T>) => void;
/**
* Fetches a random value from the provided array.
* @param arr - The array to select a random value from.
* @param fallbackValue - A fallback value to return if the array is empty or undefined.
* @returns A random value from the array or the fallback value.
*/
declare const getRandomValFromArray: <T>(arr: T[], fallbackValue: T) => T;
/**
* Returns an array of numbers starting from the specified start value and containing the specified count of elements.
* @param start The starting value of the range.
* @param count The number of elements in the range.
* @returns An array of numbers representing the range.
*/
declare const getRange: (start: number, count: number) => number[];
/**
* Returns an array of unique elements from the input array based on the specified property.
* @param array The input array.
* @param property The property to compare for uniqueness.
* @returns An array of unique elements.
*/
declare const getUniqueObjects: (array: Array<any>, property: string) => any[];
/**
* Selects an element from a list of provided items based on the specified index.
*
* @template T - The type of items in the list.
* @param {number} index - The index of the item to select.
* @param {...T[]} items - The list of items from which to select.
* @returns {(T | undefined)} - The selected item if the index is valid, otherwise undefined.
*
* @example
* const result = selectFromList(2, "one", "two", "three");
* console.log(result); // Output: "three"
*/
declare const selectFromList: <T>(index: number, ...items: T[]) => T | undefined;
/**
* Randomizes the order of elements in an array using the Fisher-Yates shuffle algorithm.
*
* @param array - The array to shuffle.
* @returns A new array with the same elements in random order.
*
* @example
* ```typescript
* shuffleArray([1, 2, 3, 4, 5]); // Returns: [3, 1, 5, 2, 4] (random order)
* shuffleArray(['a', 'b', 'c']); // Returns: ['c', 'a', 'b'] (random order)
* shuffleArray([]); // Returns: []
* ```
*/
declare const shuffleArray: <T>(array: T[]) => T[];
/**
* Converts a Blob object to a Base64-encoded string using a Promise in React Native.
* @param blob - The Blob object to convert.
* @returns A Promise that resolves with the Base64-encoded string or rejects with an error.
*/
declare function convertBlobToBase64NativeAsync(blob: Blob): Promise<string>;
/**
* Converts a Blob object to a Base64-encoded string in the web environment.
* @param blob - The Blob object to convert.
* @returns A Promise that resolves with the Base64-encoded string or rejects with an error.
*/
declare function convertBlobToBase64WebAsync(blob: Blob): Promise<string>;
/**
* Universal base64 decoder for Node.js, browser, and React Native
*
* Decodes a base64-encoded string to a UTF-8 string in any JS environment.
* @param base64 - The base64-encoded string
* @returns The decoded UTF-8 string
*/
declare function decodeBase64ToString(base64: string): string;
/**
* Universal base64 encoder for Node.js, browser, and React Native
*
* Encodes a UTF-8 string to a base64-encoded string in any JS environment.
* @param str - The UTF-8 string to encode
* @returns The base64-encoded string
*/
declare function encodeStringToBase64(str: string): string;
/**
* Validates if a string is a valid base64-encoded string
*
* Checks if the string contains only valid base64 characters and has proper padding.
* @param str - The string to validate
* @returns `true` if the string is valid base64, otherwise `false`
*/
declare function isValidBase64(str: string): boolean;
/**
* Checks if a value is a valid Blob object.
* @param value - The value to check.
* @returns `true` if the value is a valid Blob, otherwise `false`.
*/
declare function isValidBlob(value: unknown): boolean;
declare const binaryToHex: (binary: string) => string;
/**
* Parse headers into an object
*
* @param rawHeaders Headers needing to be parsed
*
* @returns Headers parsed into an object
*/
declare function parseHeaders(rawHeaders: string): Record<string, string | string[]>;
declare function parsePropPath(name: string): string[];
/**
* Options for formatting the abbreviated number's suffix.
*/
interface AbbreviateOptions {
/**
* Specifies the case of the suffix. Accepts 'lower' for lowercase or 'upper' for uppercase.
* If not provided, the suffix defaults to uppercase.
*/
case?: "lower" | "upper";
/**
* Specifies the rounding method. Accepts 'up' for rounding up, 'down' for rounding down, 'none' for no rounding.
* If not provided, the default is 'none'.
*/
rounding?: "up" | "down" | "none";
}
/**
* Enum for suffixes used in number abbreviation.
*/
declare enum AbbreviateNumberSuffix {
NONE = "",
K = "K",
M = "M",
B = "B",
T = "T",
P = "P",
E = "E"
}
/**
* Abbreviates a number to a more readable format using suffixes for thousands (K), millions (M), billions (B), and larger values.
* The function can handle both number and string inputs, and provides an option to format the suffix in lowercase or uppercase.
*
* @param value - The number or string to be abbreviated. If the value is `undefined`, the function returns an empty string.
* If the value cannot be converted to a number, the function returns 'Invalid input'.
* @param options - An optional parameter to specify the formatting options for the suffix.
* @returns The abbreviated number with an appropriate suffix or an error message if the input is invalid.
*
* @example
* ```typescript
* // Basic usage with number input
* abbreviateNumber(123); // "123"
* abbreviateNumber(1234); // "1.2K"
* abbreviateNumber(1234567); // "1.2M"
* abbreviateNumber(1234567890); // "1.2B"
*
* // Basic usage with string input
* abbreviateNumber("1234567890123"); // "1.2T"
*
* // Using options to format the suffix in lowercase
* abbreviateNumber(1234567, { case: 'lower' }); // "1.2m"
*
* // Using options to format the suffix in uppercase
* abbreviateNumber(1234567, { case: 'upper' }); // "1.2M"
*
* // Handling undefined input
* abbreviateNumber(undefined); // ""
*
* // Handling invalid input
* abbreviateNumber("invalid input"); // "Invalid input"
* ```
*/
declare const abbreviateNumber: (value: string | number | undefined, options?: AbbreviateOptions) => string;
/**
* Enum representing prefixes for labels when there is a single item.
*/
declare enum SingleItemLabelPrefix {
Only = "Only",
Exclusive = "Exclusive to",
Solely = "Solely in"
}
/**
* Enum representing prefixes for labels when there are multiple items.
*/
declare enum MultipleItemsLabelPrefix {
IncludedIn = "Included in",
FoundWithin = "Found in",
PresentIn = "Present in"
}
/**
* Enum for conjunctions used between items in a list.
*/
declare enum ListConjunction {
And = "and",
AsWellAs = "as well as",
AlongWith = "along with"
}
/**
* Parameters for composing a label from an array of items.
* @template T - The type of each item in the array.
*/
interface LabelCompositionParams<T> {
/**
* Array of items to compose into the label.
*/
items: T[];
/**
* Key in each item to be used for label generation.
*/
labelKey: keyof T;
/**
* Prefix to use if there is only one item. Defaults to SingleItemLabelPrefix.Only.
*/
singleItemPrefix?: SingleItemLabelPrefix | keyof typeof SingleItemLabelPrefix;
/**
* Prefix to use for multiple items. Defaults to MultipleItemsLabelPrefix.FoundWithin.
*/
multipleItemsPrefix?: MultipleItemsLabelPrefix | keyof typeof MultipleItemsLabelPrefix;
/**
* Conjunction to use when listing items, applied before the last item. Defaults to ListConjunction.And.
*/
conjunctionWord?: ListConjunction | keyof typeof ListConjunction;
}
/**
* Composes a descriptive label from an array of objects by concatenating values of a specified key in each object.
* The label adjusts automatically based on the number of items and provides flexibility to customize prefixes and conjunctions.
*
* @template T - The type of each item in the items array.
* @param {LabelCompositionParams<T>} params - Configuration parameters for generating the label.
* @returns {string} A formatted string label based on the provided items and options.
*
* @example
* // Example usage with a simple array of products
* interface Product { name: string; }
* const products: Product[] = [
* { name: "Apple" },
* { name: "Banana" },
* { name: "Cherry" },
* ];
*
* const label = composeLabelFromItems({
* items: products,
* labelKey: "name",
* singleItemPrefix: "Only",
* multipleItemsPrefix: "FoundWithin",
* conjunctionWord: "And",
* });
* // Output: "Found in Apple, Banana and Cherry:"
*/
declare const composeLabelFromItems: <T>({ items, labelKey, singleItemPrefix, multipleItemsPrefix, conjunctionWord, }: LabelCompositionParams<T>) => string;
declare enum RangeOrAmountEnum {
None = " ",
Range = "Range",
Amount = "Amount"
}
declare enum PercentagePrefixEnum {
Empty = " ",
UpTo = "up to",
About = "about",
Around = "around",
Approximately = "approximately"
}
interface FormatDetailOptions {
details: string;
formatAsRangeOrAmount?: RangeOrAmountEnum | keyof typeof RangeOrAmountEnum;
percentagePrefix?: PercentagePrefixEnum | keyof typeof PercentagePrefixEnum;
percentageSuffix?: string;
minPercent?: number;
maxPercent?: number;
percent?: number;
}
/**
* Formats a detail string with optional range, percentage, prefix, and suffix.
* This function allows customization in formatting a detail string based on the specified options,
* including support for range, percentage, or additional prefix/suffix customization.
*
* - If `formatAsRangeOrAmount` is set to `RangeOrAmountEnum.Range`, it formats as a range using
* `minPercent` and `maxPercent`.
* - If `formatAsRangeOrAmount` is set to `RangeOrAmountEnum.Amount`, it formats as a single percentage value.
* - If `formatAsRangeOrAmount` is set to `RangeOrAmountEnum.None`, only `details` is returned.
* - Optional parentheses are added around the range or percentage if `percentagePrefix` or `percentageSuffix` is specified.
*
* ### Formatting Examples:
*
* 1. **Range with Prefix and Suffix**
* - Input: `{ details: "Usage", formatAsRangeOrAmount: RangeOrAmountEnum.Range, percentagePrefix: PercentagePrefixEnum.UpTo, minPercent: 10, maxPercent: 20, percentageSuffix: "% or higher" }`
* - Output: `(up to 10 - 20% or higher) Usage`
*
* 2. **Single Percentage Amount**
* - Input: `{ details: "Rate", formatAsRangeOrAmount: RangeOrAmountEnum.Amount, percent: 50 }`
* - Output: `(50%) Rate`
*
* 3. **No Range or Amount Formatting (Details Only)**
* - Input: `{ details: "Performance", formatAsRangeOrAmount: RangeOrAmountEnum.None }`
* - Output: `Performance`
*
* 4. **Range without Prefix or Suffix**
* - Input: `{ details: "Range Detail", formatAsRangeOrAmount: RangeOrAmountEnum.Range, minPercent: 15, maxPercent: 25 }`
* - Output: `(15 - 25%) Range Detail`
*
* 5. **Amount with Prefix Only**
* - Input: `{ details: "Limit", formatAsRangeOrAmount: RangeOrAmountEnum.Amount, percent: 75, percentagePrefix: PercentagePrefixEnum.About }`
* - Output: `(about 75%) Limit`
*
* @param options - Options to control the detail formatting.
* @param options.details - The base detail string to format.
* @param options.formatAsRangeOrAmount - Specifies whether to format as a range, amount, or none.
* Defaults to `RangeOrAmountEnum.None`.
* @param options.percentagePrefix - Optional prefix to add before the percentage or range.
* Defaults to `PercentagePrefixEnum.Empty`.
* @param options.percentageSuffix - Optional suffix to add after the percentage or range.
* @param options.percent - The percentage value to use if `formatAsRangeOrAmount` is `RangeOrAmountEnum.Amount`.
* Defaults to `0`.
* @param options.minPercent - The minimum percentage for the range if `formatAsRangeOrAmount` is `RangeOrAmountEnum.Range`.
* Defaults to `0`.
* @param options.maxPercent - The maximum percentage for the range if `formatAsRangeOrAmount` is `RangeOrAmountEnum.Range`.
* Defaults to `0`.
*
* @returns A formatted string based on the specified range, percentage, prefix, suffix, and details.
*/
declare const formatRangeOrPercentage: (options: FormatDetailOptions) => string;
/**
* Returns the first word of a string capitalized.
*
* @param str - The input string.
* @returns The first word of the input string, with the first letter capitalized and the rest in lowercase.
* @throws If an error occurs during the process.
*/
declare const getFirstWordCapitalized: (str: string) => string;
interface ErrorMessages {
[key: string]: string | string[] | unknown;
message?: string[];
}
/**
* Retrieves the first error message found for any of the given fields.
*
* @param fieldsToCheck - A string or an array of strings representing the fields to check.
* @param errors - An object containing error messages.
* @returns The first error message found for any of the given fields, or undefined if not found.
*/
declare const getMessageByField: (fieldsToCheck: string | string[], errors: ErrorMessages) => string | undefined;
type ErrorObject = Record<string, unknown>;
/**
* Retrieves a specific message from an error object based on a given field.
*
* @param field - The field value to look for in the error messages.
* @param obj - An object containing error messages.
* @param nameOfField - The key name within the error object that holds the messages array.
* @returns The message containing the field value, or null if not found.
*/
declare const getMessageFromObject: (field: string | number | boolean | null | undefined, obj: ErrorObject, nameOfField?: string) => string | null | undefined;
declare enum ProtocolPrefixEnum {
HTTPS = "https://",
HTTP = "http://",
NONE = ""
}
type ProtocolPrefix = `${ProtocolPrefixEnum}` | ProtocolPrefixEnum;
interface GenerateAllowedOriginsOptions {
includeWww?: boolean;
validateDomains?: boolean;
}
/**
* Generates an array of allowed origin URLs based on the provided domains and prefixes.
* Automatically excludes `www.` for localhost domains.
* @param domains - An array of domain strings.
* @param prefixes - An array of URL prefixes.
* @param options - Options to customize the generation.
* @returns An array of unique, fully qualified URLs.
*/
declare const generateAllowedOrigins: (domains: string[], prefixes?: ProtocolPrefix[], options?: GenerateAllowedOriginsOptions) => string[];
interface Card {
brand: string;
number: string;
cvv: string;
expirationDate: string;
}
/**
* Generates a random Stripe card object for testing purposes.
* @returns A card object with brand, number, cvv, and expirationDate
*/
declare function generateStripeCard(): Card;
/**
* Finds an item in an array based on a specific letter and optional filter text.
* @param letter - The letter to search for in the item's key value.
* @param array - The array of items to search through.
* @param key - The key to check in each item. Defaults to "name".
* @param index - The index of the letter to check in the key value. Defaults to 0.
* @param filterText - The optional filter text to match against the key value.
* @returns True if an item is found that matches the letter and filter text, false otherwise.
*/
declare const hasItemByLetterAndFilter: (letter: string, array: Array<any>, key?: string, index?: number, filterText?: string) => boolean;
declare const jsonContainsNewLine: (jsonInput: string | object) => boolean;
interface TransitionalOptions {
option: string;
description: string;
}
declare function createTransitionalMessage(version: string, name: string, messageTemplate?: string): (options: TransitionalOptions) => string;
/**
* Enum representing text and background color options.
*
* @enum {string}
* @property {string} green - Green text color.
* @property {string} red - Red text color.
* @property {string} blue - Blue text color.
* @property {string} yellow - Yellow text color.
* @property {string} magenta - Magenta text color.
* @property {string} bgGreen - Green background color with white text.
* @property {string} bgRed - Red background color with white text.
* @property {string} bgBlue - Blue background color with white text.
* @property {string} reset - Resets formatting to default.
*/
declare enum TColor {
green = "green",
red = "red",
blue = "blue",
yellow = "yellow",
magenta = "magenta",
bgGreen = "bgGreen",
bgRed = "bgRed",
bgBlue = "bgBlue",
reset = "reset"
}
/**
* Type representing valid values of the TColor enum.
*
* This type includes both text and background color options.
*/
type TColorValue = keyof typeof TColor;
/**
* Logs a message to the console with the specified color.
*
* @param {TColor | TColorValue} color - The color to use for the log message.
* @param {string} message - The message to log.
* @param {Record<string, unknown>} [data] - Optional additional data to log alongside the message.
*/
declare const log: (color: TColor | TColorValue, message: string, data?: Record<string, unknown>) => void;
/**
* Logs a message with a specified color.
*
* @param {string} message - The message to log.
* @param {TColorValue} [color='bgBlue'] - The color value to use for the message.
*/
declare const logMessage: (message: string, color?: TColorValue) => void;
/**
* Logs a message based on a condition (green for true, red for false).
*
* @param {string} message - The message to log.
* @param {boolean} condition - The condition to determine the color of the message.
*/
declare const logCondition: (message: string, condition: boolean) => void;
/**
* Logs error messages with red color.
*
* @param {string} functionName - The name of the function where the error occurred.
* @param {string | Record<string, unknown>} error - The error message or object to log.
*/
declare const logError: (functionName: string, error: string | Record<string, unknown> | object) => void;
/**
* Logs messages for a function, including variables (JSON or normal variables).
*
* @param {string} functionName - The name of the function being logged.
* @param {Record<string, unknown> | string | number | boolean} variables - Variables to log.
* @param {string} [message] - An optional message to log alongside the variables.
* @param {TColorValue} [color='bgBlue'] - The color to use for the log message.
*/
declare const logFunction: (functionName: string, variables: Record<string, unknown> | string | number | boolean, message?: string, color?: TColorValue) => void;
/**
* Logs a separator for better readability in the console.
*/
declare const logSeparator: () => void;
/**
* Logs the start of a process or function with an optional file name.
*
* @param {string} functionName - The name of the function or process being started.
* @param {string} [fileName] - An optional file name to provide context.
*/
declare const logStart: (functionName: string, fileName?: string) => void;
/**
* Logs the end of a process or function with an optional file name.
*
* @param {string} functionName - The name of the function or process being ended.
* @param {string} [fileName] - An optional file name to provide context.
*/
declare const logEnd: (functionName: string, fileName?: string) => void;
type Reducer = (descriptor: PropertyDescriptor, name: string) => false | PropertyDescriptor | undefined;
declare const reduceDescriptors: (obj: object, reducer: Reducer) => void;
type TimeUnits = "ms" | "s";
interface WaitFor {
(value: number, timeUnits?: TimeUnits, logDuration?: boolean): Promise<void>;
}
/**
* Waits for a specified amount of time before resolving a promise.
* @param value - The value representing the time to wait.
* @param timeUnits - Optional. The units of time for the value. Defaults to "ms" if not provided.
* @param logDuration - Optional. Specifies whether to log the duration of the wait. Defaults to false if not provided.
* @returns A promise that resolves after the specified time has elapsed.
*/
declare const waitFor: WaitFor;
/**
* Wraps a function to handle optional arguments as an array.
*
* @template T - The tuple type of the required arguments.
* @template U - The type of the optional arguments.
* @param {(...args: [...T, U[]]) => void} fn - The function to wrap.
* @returns {(...args: [...T, ...U[]]) => void} - The wrapped function.
*
* @example
* const wrappedFn = wrapFunctionWithOptionalArgs((a: number, b: number, options: number[]) => {
* console.log(a, b, options);
* });
* wrappedFn(1, 2, 3, 4, 5); // Output: 1 2 [3, 4, 5]
*/
declare const wrapFunctionWithOptionalArgs: <T extends unknown[], U>(fn: (...args: [...T, U[]]) => void) => (...args: [...T, ...U[]]) => void;
declare const ensureValidStyle: (cssString: string) => string;
declare const safeCssProperties: string[];
/**
* Calculates the percentage of a partial value compared to a whole value.
*
* @param partial The partial value.
* @param whole The whole value.
* @param truncate Optional. If true, truncates the result to an integer.
* @returns The percentage value.
* @throws Error if either partial or whole is not a number, or if whole is zero.
*/
declare function calculatePercentage(partial: number, whole: number, truncate?: boolean): number;
/**
* Restricts a value between a minimum and maximum bound.
*
* @param num - The number to clamp.
* @param min - The minimum bound.
* @param max - The maximum bound.
* @returns The clamped value.
*
* @example
* ```typescript
* clamp(5, 0, 10); // Returns: 5
* clamp(-5, 0, 10); // Returns: 0
* clamp(15, 0, 10); // Returns: 10
* clamp(3.14, 0, 5); // Returns: 3.14
* ```
*/
declare const clamp: (num: number, min: number, max: number) => number;
/**
* Formats a number with comma separators for thousands.
*
* @param num - The number to format.
* @returns The formatted number string with commas.
*
* @example
* ```typescript
* formatNumberWithCommas(1000); // Returns: "1,000"
* formatNumberWithCommas(1234567); // Returns: "1,234,567"
* formatNumberWithCommas(100); // Returns: "100"
* formatNumberWithCommas(1000.5); // Returns: "1,000.5"
* ```
*/
declare const formatNumberWithCommas: (num: number) => string;
interface GetAspectRatioParams {
width: number;
aspectRatio?: AspectRatioType;
orientation?: "landscape" | "portrait";
}
declare enum AspectRatioEnum {
"4:3" = "4:3",
"16:9" = "16:9",
"1:1" = "1:1",
"3:2" = "3:2",
"8:5" = "8:5"
}
type AspectRatioType = keyof typeof AspectRatioEnum;
interface GetAspectRatioResult {
height: number;
width: number;
}
declare const getAspectRatio: (params: GetAspectRatioParams) => GetAspectRatioResult;
/**
* Calculates the average of an array of numbers.
*
* @param {number[]} nums - The array of numbers to calculate the average of.
* @returns {number} The average of the numbers in the array.
* @throws {Error} If the input is not a non-empty array of numbers.
* @throws {Error} If any element in the array is not a valid number.
*/
declare function getAverage(arr: number[]): number;
/**
* Rounds a number to a specified number of decimal places.
*
* @param num - The number to round.
* @param decimals - The number of decimal places to round to. Defaults to 0.
* @returns The rounded number.
*
* @example
* ```typescript
* roundToDecimal(3.14159, 2); // Returns: 3.14
* roundToDecimal(3.14159, 0); // Returns: 3
* roundToDecimal(3.5); // Returns: 4
* roundToDecimal(3.4); // Returns: 3
* ```
*/
declare const roundToDecimal: (num: number, decimals?: number) => number;
type AnyObject = {
[key: ObjectIndexType]: any;
} & Record<string, any>;
type PrimitiveType = number | string | boolean | symbol | bigint;
type NestedValueType = PrimitiveType | AnyObject;
type NestedRecord = Record<string, NestedValueType>;
type MergeableValue = NestedValueType | NestedRecord | MergeableValue[] | null | undefined;
type OptionalMergeableObject = Record<string, MergeableValue> | undefined | null;
type MergeableInput = OptionalMergeableObject | OptionalMergeableObject[];
type AssignValueCallback = (payload: AnyObject, key: string | number, val: NestedRecord) => NestedRecord;
declare function assignValue(val: unknown, key: string | number, payload: AnyObject, callback: AssignValueCallback): void;
/**
* Binds a function to a specific context.
*
* @template T - The type of the function.
* @param {T} fn - The function to bind.
* @param {unknown} thisArg - The context to bind the function to.
* @returns {(...args: Parameters<T>) => ReturnType<T>} - The bound function.
*/
declare function bind<T extends (...args: unknown[]) => unknown>(fn: T | ((...args: unknown[]) => unknown), thisArg: unknown): (...args: Parameters<T>) => ReturnType<T>;
/**
* Creates a deep copy of an object or array.
*
* ✅ Works in Node.js, React, and React Native.
*
* @example
* const obj = { a: 1, b: { c: 2 } };
* const cloned = deepClone(obj);
* obj.b.c = 3;
* console.log(cloned.b.c) // Still 2
*
* const arr = [1, [2, 3], { a: 4 }];
* const clonedArr = deepClone(arr);
* arr[1][0] = 5;
* console.log(clonedArr[1][0]) // Still 2
*
* @param value - The value to deep clone
* @returns A deep copy of the value
*/
declare const deepClone: <T>(value: T) => T;
declare const extend: <T, U>(a: T, b: U, thisArg?: AnyObject, { allOwnKeys }?: {
allOwnKeys?: boolean | undefined;
}) => T & U;
/**
* Interface for the return type of the extractKeysAndValuesFromRecord function.
*
* @template K - Type of the keys in the record.
* @template V - Type of the values in the record.
*/
interface ReturnTypeForValuesFromRecord<K extends string, V> {
keys: K[];
values: V[];
}
/**
* Extracts the keys and values from a record and returns them as arrays.
*
* @template T - Type of the record being passed in.
*
* @param {T} record - The record from which to extract keys and values.
* @returns {ReturnTypeForValuesFromRecord<keyof T & string, T[keyof T]>} An object containing the keys and values arrays.
*/
declare function extractKeysAndValues<T extends Record<string, unknown>>(record: T): ReturnTypeForValuesFromRecord<keyof T & string, T[keyof T]>;
declare function findKey<T extends object>(obj: T, key: string | number): keyof T | null;
type ObjectWithMethods = {
[key: string]: Function;
};
declare const freezeMethods: (obj: ObjectWithMethods) => void;
/**
* Retrieves a specific value from an object based on a given key.
*
* @param key - The key to search for in the object.
* @param obj - The object containing the values.
* @returns The value associated with the given key, or null if not found.
*/
declare function getValueFromObject<T>(key: string, obj: Record<string, T>): T | null;
type MergedValue = MergeableValue | Record<string, MergeableValue>;
declare function merge(...objs: MergeableInput[]): Record<string, MergeableValue>;
/**
* Merges two nested objects together.
*
* @param oldObj - The original object to merge.
* @param newObj - The new object to merge.
* @returns The merged object.
*/
declare const mergeObjects: (oldObj: AnyObject, newObj: AnyObject) => AnyObject;
declare const toFlatObject: (sourceObj: object | null, destObj?: Record<string, unknown>, filter?: ((obj: object) => boolean) | undefined, propFilter?: ((prop: string, obj: object, destObj: Record<string, unknown>) => boolean) | undefined) => Record<string, unknown>;
declare const toObjectSet: (arrayOrString: unknown[] | string, delimiter?: string) => {
[key: string]: boolean;
};
/**
* Parses a query string into an object of key-value pairs.
*
* @param queryString - The query string to parse. It may include a leading '?' which will be removed automatically.
* @returns An object where keys are query parameter names and values are either a string or an array of strings if the parameter appears multiple times.
*
* @example
* ```typescript
* const queryString = '?foo=bar&baz=qux&foo=baz';
* const result = parseQueryString(queryString);
* console.log(result);
* // Output: { foo: ['bar', 'baz'], baz: 'qux' }
* ```
*/
declare const parseQueryString: (queryString: string) => Record<string, string | string[]>;
/**
* Converts an object of query parameters into a URL-encoded query string.
* This function filters out keys with `undefined` or `null` values, so only defined parameters
* will be included in the final query string.
*
* @param query - An optional object containing key-value pairs for query parameters.
* - `key: string`: The query parameter name.
* - `value: string | number | boolean | null | undefined | ArrayTypeToParse`: The value of the query parameter.
* If the value is `null` or `undefined`, it will be excluded from the final query string.
* @returns A string representing the query parameters in URL-encoded format.
* - If `query` is undefined or empty, an empty string `""` will be returned.
* - If all values in the `query` object are `null` or `undefined`, an empty string `""` will be returned.
*
* @example
* Basic usage:
* ```typescript
* toQueryString({ name: "John", age: 30 });
* // Returns: "?name=John&age=30"
* ```
*
* Filtering out undefined or null values:
* ```typescript
* toQueryString({ name: "Alice", age: null, active: true });
* // Returns: "?name=Alice&active=true"
* ```
*
* Handling empty or undefined input:
* ```typescript
* toQueryString();
* // Returns: ""
*
* toQueryString({});
* // Returns: ""
*
* toQueryString({ name: null });
* // Returns: ""
* ```
*
* Handling arrays and objects in filters:
* ```typescript
* toQueryString({ filters: [{ type: "category", value: "books" }, { type: "price", value: "low" }] });
* // Returns: "?filters[0][type]=category&filters[0][value]=books&filters[1][type]=price&filters[1][value]=low"
* ```
*/
type ArrayTypeToParse = {
[key: string]: string | number | boolean | null | undefined | string[];
}[] | string[] | number[] | boolean[] | null[] | undefined[];
declare const toQueryString: (query?: Record<string, string | number | boolean | null | undefined | ArrayTypeToParse | Record<string, string | number | boolean>>) => string;
/**
* Capitalizes the first letter of a string.
*
* ✅ Works in Node.js, React, and React Native.
*
* @example
* capitalize("hello world") // "Hello world"
* capitalize("WORLD") // "WORLD"
* capitalize("") // ""
*
* @param str - The input string to capitalize
* @returns A new string with the first letter capitalized
*/
declare const capitalize: (str: string) => string;
/**
* Converts a dash-separated string to camel case.
*
* @param dashName - The dash-separated string to convert.
* @returns The camel case version of the input string.
*/
declare function dashToCamelCase(dashName: string): string;
declare const endsWith: (str: string, searchString: string, position?: number) => boolean;
/**
* Converts a string to kebab-case (lowercase with hyphens).
*
* @param str - The string to convert to kebab-case.
* @returns The string in kebab-case format.
*
* @example
* ```typescript
* kebabCase("hello world"); // Returns: "hello-world"
* kebabCase("HelloWorld"); // Returns: "hello-world"
* kebabCase("hello_world"); // Returns: "hello-world"
* kebabCase("helloWorld"); // Returns: "hello-world"
* ```
*/
declare const kebabCase: (str: string) => string;
declare const matchAll: (regExp: RegExp, str: string) => RegExpMatchArray[];
declare const pluralize: (count: number, singular: string, plural: string) => string;
/**
* Removes new lines from a JSON string or object.
* @param jsonInput The JSON string or object to remove new lines from.
* @returns Returns the JSON object with new lines removed.
* @throws Throws an error if the input is not valid JSON.
*/
declare const removeNewLinesFromJson: (jsonInput: string | Record<string, unknown>) => Record<string, unknown>;
/**
* Removes all new line characters from a given string.
* @param inputString - The input string to remove new lines from.
* @returns The input string with all new lines removed.
*/
declare const removeNewLinesFromString: (inputString: string) => string;
/**
* Removes spaces from a JSON object or string.
*
* @param jsonInput - The JSON object or string to remove spaces from.
* @returns The JSON object with spaces removed.
* @throws {Error} If the input is not a valid JSON.
*/
declare const removeSpacesFromJson: (jsonInput: string | Record<string, unknown>) => Record<string, unknown>;
/**
* Removes all spaces from a given string.
* @param inputString - The string from which to remove spaces.
* @returns The input string with all spaces removed.
*/
declare const removeSpacesFromString: (inputString: string) => string;
declare const removeSymbolAt: (str: string, symbol: string, position?: number) => string;
/**
* Converts a string to a URL-friendly slug.
*
* @param str - The string to convert to a slug.
* @returns A URL-friendly slug string.
*
* @example
* ```typescript
* slugify("Hello World!"); // Returns: "hello-world"
* slugify("This is a Test String"); // Returns: "this-is-a-test-string"
* slugify("Special@#$%Characters"); // Returns: "special-characters"
* slugify("Multiple Spaces"); // Returns: "multiple-spaces"
* ```
*/
declare const slugify: (str: string) => string;
declare const toCamelCase: (str: string) => string;
/**
* Truncates a string to a specified length and appends ellipsis if needed.
*
* @param str - The string to truncate.
* @param length - The maximum length of the string (including ellipsis).
* @param ellipsis - Optional. The ellipsis string to append. Defaults to "…".
* @returns The truncated string with ellipsis if needed.
*
* @example
* ```typescript
* truncate("Hello world", 8); // Returns: "Hello w…"
* truncate("Short", 10); // Returns: "Short"
* truncate("Very long string that needs truncation", 15); // Returns: "Very long str…"
* truncate("Test", 3, "!!!"); // Returns: "!!!"
* ```
*/
declare const truncate: (str: string, length: number, ellipsis?: string) => string;
/**
* Converts a video timestamp string to seconds.
*
* @param timestamp - The video timestamp string in the format "HH:MM:SS".
* @returns The number of seconds represented by the timestamp, or NaN if the timestamp is invalid.
*/
declare function convertVideoTimeStampToSeconds(timestamp: string): number;
/**
* Creates a debounced function that delays execution until after a specified wait time.
*
* ✅ Works in Node.js, React, and React Native.
*
* @example
* const debouncedSearch = debounce(searchFunction, 300);
* debouncedSearch('query') // Will only execute after 300ms of no calls
*
* // In React/React Native:
* const handleInputChange = debounce((value) => {
* // API call or expensive operation
* }, 500);
*
* @param fn - The function to debounce
* @param delay - The number of milliseconds to delay
* @returns A debounced version of the function
*/
declare const debounce: <T extends (...args: unknown[]) => unknown>(fn: T, delay: number) => (...args: Parameters<T>) => void;
/**
* Creates a throttled function that limits the rate at which the provided function can be called.
* The function will be called at most once per specified delay period.
*
* @param fn - The function to throttle.
* @param delay - The number of milliseconds to throttle by.
* @returns A throttled version of the function.
*
* @example
* ```typescript
* const throttledScroll = throttle(handleScroll, 100);
* window.addEventListener('scroll', throttledScroll);
*
* // In React/React Native:
* const handleResize = throttle(() => {
* // Update layout
* }, 250);
* ```
*/
declare const throttle: <T extends (...args: unknown[]) => unknown>(fn: T, delay: number) => (...args: Parameters<T>) => void;
declare const hasOwnProp: (obj: object, prop: string | symbol) => boolean;
declare const isBoolean: (thing: unknown) => boolean;
declare function isBuffer(val: {
constructor: {
isBuffer: (arg0: any) => any;
} | null;
} | null): any;
declare function isArrayBufferView(val: {
buffer: any;
}): any;
declare const isArrayBuffer: (thing: unknown) => boolean;
type GlobalPayload = typeof globalThis | typeof self | typeof window | typeof global;
declare const isGlobalDefined: GlobalPayload;
declare const isContextDefined: (context: GlobalPayload) => boolean;
declare const isDate: (thing: unknown) => boolean;
/**
* Checks if two objects are deeply equal.
*
* @param obj1 - The first object to compare.
* @param obj2 - The second object to compare.
* @returns `true` if the objects are deeply equal, `false` otherwise.
*/
declare function isDeepEqual(obj1: Record<string, any>, obj2: Record<string, any>): boolean;
declare const isEmpty: (value: unknown) => boolean;
declare const isFile: (thing: unknown) => boolean;
interface CustomFormDataLike {
append: (arg0: string, arg1: unknown) => void;
toString: () => string;
}
declare const isFormData: (thing: unknown) => thing is CustomFormDataLike | FormData;
declare function isFunction(value: unknown): value is Function;
/**
* Checks if a string is a valid JSON by attempting to parse it.
* @param str The string to check.
* @returns Returns the parsed JSON object if the string is valid JSON, otherwise returns false.
*/
declare const isJson: (value: string | object) => Record<string, unknown> | boolean;
/**
* Checks if a value is of type number.
*
* This function is a specialized version of `typeOfTest` that checks if the provided value is a number.
*
* @param {unknown} thing - The value to check.
* @returns {boolean} - Returns `true` if the value is a number, otherwise `false`.
*
* @example
* // Returns true
* isNumber(123);
*
* @example
* // Returns false
* isNumber("123");
*
* @example
* // Returns false
* isNumber({});
*/
declare const isNumber: (thing: unknown) => boolean;
/**
* Checks if a value is numeric.
*
* This function determines if the provided value is a number or a numeric string.
* It also checks for floating-point numbers.
*
* @param {unknown} n - The value to check.
* @returns {boolean} - Returns `true` if the value is numeric, otherwise `false`.
*
* @example
* // Returns true
* isNumeric(123);
*
* @example
* // Returns true
* isNumeric("123");
*
* @example
* // Returns true
* isNumeric(1.23);
*
* @example
* // Returns false
* isNumeric("abc");
*
* @example
* // Returns false
* isNumeric({});
*
* @example
* // Returns false
* isNumeric(" 123 ");
*/
declare const isNumeric: (n: unknown) => boolean;
/**
* Checks if the given value is an object.
*
* @param {unknown} thing - The value to check.
* @returns {boolean} - Returns `true` if the value is an object and not `null`, otherwise `false`.
*/
declare const isObject: (thing: unknown) => boolean;
/**
* Checks if a value is a plain object.
*
* @param value - The value to check.
* @returns `true` if the value is a plain object, `false` otherwise.
*/
declare const isPlainObject: (value: any) => value is AnyObject;
declare function isRegExp(value: unknown): value is RegExp;
declare function isString(value: unknown): value is string;
declare const isUndefined: (thing: unknown) => boolean;
declare const isValidBinary: (binary: string) => boolean;
/**
* Checks if a CSS string contains valid style declarations.
*
* @param cssString - The CSS string to validate.
* @param validProperties - An optional array of additional valid CSS properties.
* @returns A boolean indicating whether the CSS string is valid.
*/
declare const isValidStyle: (cssString: string, validProperties?: string[]) => boolean;
declare const kindOf: (thing: unknown) => any;
declare const kindOfTest: (type: string) => (thing: unknown) => boolean;
declare const typeOfTest: (type: string) => (thing: unknown) => boolean;
export { AbbreviateNumberSuffix, type AbbreviateOptions, AspectRatioEnum, type AspectRatioType, type AssignValueCallback, DeduplicateInputType, type ErrorMessages, type GetAspectRatioParams, type GetAspectRatioResult, type GlobalPayload, type LabelCompositionParams, ListConjunction, type MergedValue, MultipleItemsLabelPrefix, PercentagePrefixEnum, type ProtocolPrefix, ProtocolPrefixEnum, RangeOrAmountEnum, type ReturnTypeForValuesFromRecord, SingleItemLabelPrefix, type TimeUnits, type WaitFor, abbreviateNumber, arrayToObject, assignValue, binaryToHex, bind, calculatePercentage, capitalize, chunkArray, clamp, composeLabelFromItems, convertBlobToBase64NativeAsync, convertBlobToBase64WebAsync, convertVideoTimeStampToSeconds, createTransitionalMessage, dashToCamelCase, debounce, decodeBase64ToString, deduplicate, deepClone, defaultStopWords, encodeStringToBase64, endsWith, ensureValidStyle, extend, extractKeysAndValues, filterAndSuggestItems, findKey, flattenArray, forEach, forEachEntry, formatNumberWithCommas, formatRangeOrPercentage, freezeMethods, generateAllowedOrigins, generateStripeCard, getAspectRatio, getAverage, getFirstWordCapitalized, getMessageByField, getMessageFromObject, getRandomValFromArray, getRange, getUniqueObjects, getValueFromObject, hasItemByLetterAndFilter, hasOwnProp, isArrayBuffer, isArrayBufferView, isBoolean, isBuffer, isContextDefined, isDate, isDeepEqual, isEmpty, isFile, isFormData, isFunction, isGlobalDefined, isJson, isNumber, isNumeric, isObject, isPlainObject, isRegExp, isString, isUndefined, isValidBase64, isValidBinary, isValidBlob, isValidStyle, jsonContainsNewLine, kebabCase, kindOf, kindOfTest, log, logCondition, logEnd, logError, logFunction, logMessage, logSeparator, logStart, matchAll, merge, mergeObjects, parseHeaders, parsePropPath, parseQueryString, pluralize, reduceDescriptors, removeNewLinesFromJson, removeNewLinesFromString, removeSpacesFromJson, removeSpacesFromString, removeSymbolAt, roundToDecimal, safeCssProperties, selectFromList, shuffleArray, slugify, throttle, toCamelCase, toFlatObject, toObjectSet, toQueryString, truncate, typeOfTest, waitFor, wrapFunctionWithOptionalArgs };