nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
215 lines (214 loc) • 9.42 kB
TypeScript
import type { GenericObject } from '../object/types';
import type { ClassDetails, Constructor, DelayedFn, Maybe, Primitive, VoidFn } from '../types/index';
import type { ArrayOfObjectsToStringOptions, ArrayOfPrimitivesToStringOptions, ProtoMethodOptions } from './types';
/**
* * Deeply compare two values (arrays, objects, or primitive values).
*
* @param a First value to compare.
* @param b Second value to compare.
* @returns Whether the values are deeply equal.
*/
export declare const isDeepEqual: (a: unknown, b: unknown) => boolean;
/**
* * Converts an array of objects to a string using a specific property (supports nested path to primitive values) and separator.
*
* @example
* const users = [
* { id: 1, name: { first: 'Alice' }, city: 'Bangu', },
* { id: 4, name: { first: 'Bob' }, city: 'Banguland', },
* ];
* convertArrayToString(users, { target: 'name.first', separator: ' | ' });
* // "Alice | Bob"
*
* @param array Array of objects to convert.
* @param options Options including the target property and separator.
* @returns String formed by joining the property values with the given separator.
*/
export declare function convertArrayToString<T extends GenericObject>(array: Maybe<T[]>, options: ArrayOfObjectsToStringOptions<T>): string;
/**
* * Converts an array of primitive values to a string using a custom separator.
*
* @example
* convertArrayToString(['red', 'green', 'blue'], { separator: ' - ' });
* // "red - green - blue"
*
* @example
* convertArrayToString([1, 2, 3]);
* // "1, 2, 3"
*
* @param array Array of primitive values to convert.
* @param options Optional separator configuration.
* @returns String formed by joining array elements with the given separator.
*/
export declare function convertArrayToString<T extends Primitive>(array: Maybe<T[]>, options?: ArrayOfPrimitivesToStringOptions): string;
/**
* * A generic debounce function that delays the execution of a callback.
*
* @param callback - The function to debounce.
* @param delay - The delay in milliseconds. Default is `300ms`.
* @returns A debounced version of the callback function.
*
* @example
* const debouncedSearch = debounceAction((query: string) => {
* console.log(`Searching for: ${query}`);
* }, 300);
*
* debouncedSearch('laptop'); // Executes after 300ms of inactivity.
*/
export declare function debounceAction<T extends VoidFn>(callback: T, delay?: number): DelayedFn<T>;
/**
* * A generic throttle function that ensures a callback is executed at most once per specified interval.
*
* @param callback - The function to throttle.
* @param delay - The delay in milliseconds. Default is `150ms`.
* @returns A throttled version of the callback function.
*
* @example
* const throttledResize = throttleAction(() => {
* console.log('Resized');
* }, 300);
*
* window.addEventListener('resize', throttledResize);
*/
export declare function throttleAction<T extends VoidFn>(callback: T, delay?: number): DelayedFn<T>;
/**
* * Retrieves the names of all instance methods defined directly on a class prototype.
*
* @param cls - The class constructor (not an instance).
* @returns A sorted array of instance method names.
*/
export declare function getInstanceMethodNames(cls: Constructor): string[];
/**
* * Retrieves the names of all static methods defined directly on a class constructor.
*
* @param cls - The class constructor (not an instance).
* @returns A sorted array of static method names.
*/
export declare function getStaticMethodNames(cls: Constructor): string[];
/**
* * Counts the number of instance methods defined directly on a class prototype.
*
* @param cls - The class constructor (not an instance).
* @returns The number of instance methods defined on the class prototype.
*/
export declare function countInstanceMethods(cls: Constructor): number;
/**
* * Counts the number of static methods defined directly on a class constructor.
*
* @param cls - The class constructor (not an instance).
* @returns The number of static methods defined on the class constructor.
*/
export declare function countStaticMethods(cls: Constructor): number;
/**
* * Retrieves the names of all instance getters defined directly on a class prototype.
*
* @param cls - The class constructor (not an instance).
* @returns A sorted array of instance getter names.
*/
export declare function getInstanceGetterNames(cls: Constructor): string[];
/**
* * Retrieves the names of all static getters defined directly on a class constructor.
*
* @param cls - The class constructor (not an instance).
* @returns A sorted array of static getter names.
*/
export declare function getStaticGetterNames(cls: Constructor): string[];
/**
* * Gathers detailed information about the instance and static methods of a class.
*
* @param cls - The class constructor (not an instance).
* @returns An object containing names and counts of instance and static methods.
*/
export declare function getClassDetails(cls: Constructor): ClassDetails;
/**
* * Create a deterministic JSON string representation of any value.
* - The output format matches standard JSON but with guaranteed sorted keys.
*
* @remarks
* - This function guarantees **stable, repeatable output** by:
* - Sorting all object keys alphabetically.
* - Recursively stabilizing nested objects and arrays.
* - Converting all `undefined` values into `null` so the output remains valid JSON.
* - Converting date-like objects (`Date`, `Chronos`, `Moment.js`, `Day.js`, `Luxon`, `JS-Joda`, `Temporal`) **in the same way that {@link JSON.stringify} would serialize them**, ensuring predictable and JSON-compliant output.
* - Falling back to native JSON serialization for primitives.
*
* - **Useful for:**
* - Hash generation (e.g., signatures, cache keys)
* - Deep equality checks
* - Producing predictable output across environments
*
* @param obj - The value to stringify into a deterministic JSON string.
* @returns A stable, deterministic string representation of the input.
*/
export declare function stableStringify(obj: unknown): string;
/**
* * Remove trailing or leading garbage characters **after/before JSON object or array**.
* @param str String to sanitize/strip.
* @returns Sanitized/stripped JSON string.
*/
export declare function stripJsonEdgeGarbage(str: string): string;
/**
* * Parses any valid JSON string, optionally converting stringified primitives inside (nested) arrays or objects.
*
* @typeParam T - Expected return type (default is unknown).
* @param value - The JSON string to parse.
* @param parsePrimitives - Whether to convert stringified primitives (default: `true`).
* @returns The parsed JSON value typed as `T`, or the original parsed value with optional primitive conversion.
* - Returns `{}` if parsing fails, such as when the input is malformed or invalid JSON or passing single quoted string.
*
* - *Unlike {@link https://toolbox.nazmul-nhb.dev/docs/utilities/object/parseJsonToObject parseJsonToObject}, which ensures the root value is an object,
* this function returns any valid JSON structure such as arrays, strings, numbers, or objects.*
*
* This is useful when you're not sure of the root structure of the JSON, or when you expect something other than an object.
*
* @see {@link https://toolbox.nazmul-nhb.dev/docs/utilities/object/parseJsonToObject parseJsonToObject} for strict object-only parsing.
*/
export declare const parseJSON: <T = unknown>(value: string, parsePrimitives?: boolean) => T;
/**
* * Recursively parses primitive values inside objects and arrays.
*
* @typeParam T - Expected return type after parsing (default is unknown).
* @param input - Any input value to parse recursively.
* @returns Input with primitives (strings like "true", "123") converted, typed as `T`.
*/
export declare function deepParsePrimitives<T = unknown>(input: unknown): T;
/**
* * Defines a method on any prototype — including built-in prototypes — in a safe, idempotent manner.
* - The method is non-enumerable by default and will not overwrite an existing method unless explicitly allowed.
*
* @param proto The target prototype object (e.g., String.prototype).
* @param name The method name to define on the prototype.
* @param impl The function implementation for the method.
* @param options Optional property-descriptor settings and overwrite rules.
*
* @example
* // Safely augment prototype methods by extending the global interface:
* declare global {
* interface String {
* toBang(): string;
* }
* }
*
* // Define a custom method on String.prototype
* definePrototypeMethod(String.prototype, 'toBang', function (this: String) {
* return this.toString().concat('!');
* // or
* // return this.concat('!');
* });
*
* "Hi".toBang(); // "Hi!"
*
* // Attempting to redefine without overwrite option is ignored
* definePrototypeMethod(String.prototype, 'toBang', () => 'x'); // ignored
*
* // Overwrite intentionally using the overwrite option
* definePrototypeMethod(
* String.prototype,
* 'toBang',
* function (this: String) { return this.concat('!!!'); },
* { overwrite: true }
* );
*
* "Hi".toBang(); // "Hi!!!"
*/
export declare function definePrototypeMethod<Proto extends object, Name extends keyof Proto>(proto: Proto, name: Name, impl: (...args: unknown[]) => unknown, options?: ProtoMethodOptions): void;