qstd
Version:
Standard Block component and utilities library with Panda CSS
448 lines (430 loc) • 15 kB
text/typescript
import { Locale } from 'date-fns';
/**
* Robust variadic zipWith with full type inference
*/
declare function zipWith<T extends readonly any[], R>(fn: (...args: T) => R, ...arrays: {
[K in keyof T]: T[K][];
}): R[];
/**
* Create an array of x length filled with items of type y.
* @param size
* @param fn
* @returns
*/
declare const create: <T>(size: number, fn?: (_: unknown, x: number) => T) => T[];
/**
* First list includes items that pass the predicate.
* Second list includes items that failed.
* @param xs
* @param predicate
* @returns
*/
declare const partition$1: <T>(xs: T[], predicate: (x: T) => boolean) => [T[], T[]];
/**
* Split an array into chunks of a specific size
* @param list
* @param chunkSize
* @returns
*/
declare const chunk: <T>(list: T[], chunkSize: number) => T[][];
declare const list_chunk: typeof chunk;
declare const list_create: typeof create;
declare const list_zipWith: typeof zipWith;
declare namespace list {
export { list_chunk as chunk, list_create as create, partition$1 as partition, list_zipWith as zipWith };
}
/**
* dicts are homogeneous- their values must be of the same type
* records can hold values of different types
*/
type t = Record<string, unknown> | object;
/**
* Calculate the byte size of an object
* @param o
* @returns
*/
declare function byteSizeOfObj(o: any): number;
/**
* Return an object filter with a subset of properties.
* @param r
* @param predicate
*/
declare const filter: <R extends t>(r: R, predicate: (value: R[keyof R]) => boolean) => R;
/**
* Transform the values on an object
* @param r
* @param transformFn
*/
declare const transform: <R extends t>(r: R, transformFn: (key: keyof R, value: R[keyof R]) => Record<string, any>) => R;
/**
* First object contains key/value pairs that pass the predicate.
* Second object contains key/value pairs that failed.
* @param r
* @param predicate
* @returns
*/
declare const partition: <R extends t>(r: R, predicate: (key: keyof R) => boolean) => readonly [R, R];
/**
* Check if an object exists and has keys
* @param obj
* @returns
*/
declare const exists: <O>(obj: O) => boolean;
/**
* Determine if an object is empty.
* @param obj
* @returns
*/
declare const isEmpty: <T extends t>(obj: T) => boolean;
/**
* Return an object with a subset of properties.
* @param r
* @param paths
*/
declare const pick: <R extends t, U extends keyof R>(r: R, paths: Array<U>) => Pick<R, U>;
/**
* Return an object with a subset of properties omitted.
* @param r
* @param paths
*/
declare const omit: <R extends Record<string, any>, U extends keyof R>(r: R, paths: Array<U>) => Omit<R, U>;
declare const dict_byteSizeOfObj: typeof byteSizeOfObj;
declare const dict_exists: typeof exists;
declare const dict_filter: typeof filter;
declare const dict_isEmpty: typeof isEmpty;
declare const dict_omit: typeof omit;
declare const dict_partition: typeof partition;
declare const dict_pick: typeof pick;
declare const dict_transform: typeof transform;
declare namespace dict {
export { dict_byteSizeOfObj as byteSizeOfObj, dict_exists as exists, dict_filter as filter, dict_isEmpty as isEmpty, dict_omit as omit, dict_partition as partition, dict_pick as pick, dict_transform as transform };
}
type CaseOpts = {
to: "title" | "snake" | "kebab";
clean?: boolean;
};
/**
* Split text into sentences
* @param text
* @returns
*/
declare const createSentences: (text?: string) => string[];
/**
* Count words in text
* @param text
* @returns
*/
declare const countWords: (text: string) => number;
/**
* Concatenate strings with optional delimiter
* @param xs
* @param delimiter
* @returns
*/
declare const concat: (xs: (string | undefined)[], delimiter?: string) => string;
/**
* The number of times a character appears in a string
* @param str
* @param ch
* @returns
*/
declare const countChar: (str: string, ch: string) => number;
/**
* Convert a str to specific casing
* @param text
* @param opts
* @returns
*/
declare const toCase: <T extends string>(text: string, opts: CaseOpts) => string;
declare const str_concat: typeof concat;
declare const str_countChar: typeof countChar;
declare const str_countWords: typeof countWords;
declare const str_createSentences: typeof createSentences;
declare const str_toCase: typeof toCase;
declare namespace str {
export { str_concat as concat, str_countChar as countChar, str_countWords as countWords, str_createSentences as createSentences, str_toCase as toCase };
}
type Range = {
min: number;
max: number;
};
/**
* Clamp a number within a range
* @param num
* @param range
* @returns
*/
declare const clamp: (num: number, range: Range) => number;
/**
* Format a number with comma-separated thousandths
* @param n
* @returns
*/
declare const commaSeparateThousandths: (n: number | string) => string;
/**
* Convert bytes to other units.
* @param bytes
* @param decimals
* @param binaryUnits
* @example
* ```js
* formatBytes(293489203947847, 1); // 293.5 TB
* formatBytes(1234, 0); // 1 KB
* formatBytes(4534634523453678343456, 2); // 4.53 ZB
* formatBytes(4534634523453678343456, 2, true)); // 3.84 ZiB
* formatBytes(4566744, 1); // 4.6 MB
* formatBytes(534, 0); // 534 Bytes
* formatBytes(273403407, 0); // 273 MB
* ```
* @returns
*/
declare const formatBytes: (bytes?: number, decimals?: number, binaryUnits?: boolean) => {
value?: undefined;
unit?: undefined;
display?: undefined;
} | {
value: number;
unit: string;
display?: undefined;
} | {
value: number;
unit: string;
display: string;
};
declare const int_clamp: typeof clamp;
declare const int_commaSeparateThousandths: typeof commaSeparateThousandths;
declare const int_formatBytes: typeof formatBytes;
declare namespace int {
export { int_clamp as clamp, int_commaSeparateThousandths as commaSeparateThousandths, int_formatBytes as formatBytes };
}
type Opts = {
symbol?: boolean;
};
/**
* Convert cents to USD currency string
* @param cents
* @param opts
* @returns
*/
declare const convertToUsd: (cents?: number | string, opts?: Opts) => string | undefined;
/**
* Convert dollars to cents
* @param dollars
* @returns
*/
declare const convertToCents: (dollars: string | number) => number;
declare const money_convertToCents: typeof convertToCents;
declare const money_convertToUsd: typeof convertToUsd;
declare namespace money {
export { money_convertToCents as convertToCents, money_convertToUsd as convertToUsd };
}
type DurationFormat = "compact" | "full" | "clock" | "fractional";
type DurationOptions = {
/** Format style: 'compact' (1h 2m), 'full' (1 hour 2 minutes), 'clock' (01:02:03), 'fractional' (1.4s, 1m4.4s) */
format?: DurationFormat;
/** Show zero values for intermediate units (e.g., "1h 0m 30s" vs "1h 30s") */
showZero?: boolean;
};
/**
* Formats milliseconds into human-readable duration strings
* Supports compact (1h 2m), full (`1 hour 2 minutes`), clock (`01:02:03`), and fractional (1.4s, 1m4.4s) formats
*
* @param {Object} [options={}] - Configuration options
* @param {string} [options.format="clock"] - format
* @param {boolean} [options.showZero=false] - show zero prefix
*
* @example
* formatDuration(90000) // "1:30"
* formatDuration(3661000) // "1:01:01"
* formatDuration(90000, { format: "compact" }) // "1m 30s"
* formatDuration(90000, { format: "full" }) // "1 minute 30 seconds"
* formatDuration(3600000, { format: "compact" }) // "1h"
* formatDuration(3600000, { format: "compact", showZero: true }) // "1h 0m 0s"
* formatDuration(3660000, { format: "full", showZero: true }) // "1 hour 1 minute 0 seconds"
* formatDuration(1400, { format: "fractional" }) // "1.4s"
* formatDuration(45300, { format: "fractional" }) // "45.3s"
* formatDuration(64400, { format: "fractional" }) // "1m 4.4s"
*/
declare const formatDuration: (ms: number | null, options?: DurationOptions) => string;
type DateInput = Date | string | number;
type DateFormatStyle = "iso" | "short" | "medium" | "long" | "relative" | "year";
type DateOptions = {
/** Predefined format style */
style?: DateFormatStyle;
/** Custom date-fns format string (overrides style) */
pattern?: string;
/** Include time component */
includeTime?: boolean;
};
/**
* Flexible date formatter that handles multiple input types and format styles
* Supports ISO strings, timestamps, and Date objects with intelligent defaults
* @example
* // Date formatting with smart input handling
* formatDate(new Date()) // "Dec 1, 2023"
* formatDate("2023-12-01") // "Dec 1, 2023"
* formatDate(1701388800000) // "Dec 1, 2023"
* formatDate(date, { style: "short" }) // "12/1/23"
* formatDate(date, { style: "long" }) // "December 1, 2023"
* formatDate(date, { includeTime: true }) // "Dec 1, 2023 3:30 PM"
* formatDate(date, { pattern: "yyyy-MM-dd" }) // Custom format
*/
declare const formatDate: (input: DateInput, options?: DateOptions) => string;
type DateRangeInput = Date | string | number;
type DateRangeOptions = {
/** Reference date for today checks (defaults to new Date()) */
now?: Date;
/** Show time segment when start and end are the same day (default: true) */
showTimeWhenSameDay?: boolean;
/** If true, appends (today) next to whichever date equals today (default: true) */
markToday?: boolean;
/** Custom label for today marker (default: "today") */
todayLabel?: string;
/** Separator between start and end segments (default: " - ") */
separator?: string;
/** Month text style (default: "short") */
monthFormat?: "short" | "long";
/** Lowercase am/pm in time output (default: true) */
lowercaseAmPm?: boolean;
/** Locale for date-fns formatter */
locale?: Locale;
};
/**
* Formats a date range according to thread rules:
* - Same day: "MMM d (today), h:mma - h:mma" (am/pm lowercase, hyphen between times)
* - Different day, same month/year: "MMM d - d (today), yyyy"
* - Different month, same year: "MMM d - MMM d (today), yyyy"
* - Different year: "MMM d, yyyy - MMM d, yyyy" (append (today) next to the correct day if applicable)
*
* Notes:
* - "(today)" is appended next to whichever date matches today.
* - Times are shown only when start and end are the same calendar day.
*/
declare const formatDateRange: (startInput: DateRangeInput, endInput: DateRangeInput, options?: DateRangeOptions) => string;
declare const formatThreadDateRange: (startInput: DateRangeInput, endInput: DateRangeInput, options?: DateRangeOptions) => string;
type TimeUnit = "seconds" | "minutes" | "hours" | "days" | "weeks" | "months" | "years" | "businessDays";
type TimeAdjustment = Partial<Record<TimeUnit, number>>;
/**
* Creates a new date by adding specified time units to a base date
* Defaults to current date if no base date provided
* @example
* // Date manipulation
* adjustDate({ hours: 2 }) // 2 hours from now
* adjustDate({ days: -7, hours: 3 }, someDate) // (7 days ago + 3 hours) from someDate
*/
declare const adjustDate: (adjustment: TimeAdjustment, baseDate?: Date) => Date;
/**
* Promise-based delay utility for async operations
*/
declare const sleep$1: (ms: number) => Promise<void>;
/**
* Gets the current timestamp in milliseconds
*/
declare const now: () => number;
/**
* Converts various time units to milliseconds
* @example
* const ms = toMs(5, "minutes") // Convert 5 minutes to milliseconds
*/
declare const toMs: (value: number, unit?: Exclude<TimeUnit, "businessDays">) => number;
declare const time_adjustDate: typeof adjustDate;
declare const time_formatDate: typeof formatDate;
declare const time_formatDateRange: typeof formatDateRange;
declare const time_formatDuration: typeof formatDuration;
declare const time_formatThreadDateRange: typeof formatThreadDateRange;
declare const time_now: typeof now;
declare const time_toMs: typeof toMs;
declare namespace time {
export { time_adjustDate as adjustDate, time_formatDate as formatDate, time_formatDateRange as formatDateRange, time_formatDuration as formatDuration, time_formatThreadDateRange as formatThreadDateRange, time_now as now, sleep$1 as sleep, time_toMs as toMs };
}
/**
* Throttle a function call
* @param fn
* @param ms
* @returns
*/
declare const throttle: (fn: any, ms: number) => (...args: any[]) => void;
/**
* Ensure code is only triggered once per user input.
* The debounce forces another function to wait a certain amount of time before running again.
* Its purpose is to prevent a function from being called several times in succession.
* @param fn
* @param timeout
* @returns
*/
declare const debounce: <T extends any[]>(fn: (...args: T) => any, timeout: number) => ((...args: T) => void);
/**
* Sleep for x milliseconds.
* @param ms
* @returns
*/
declare const sleep: (ms: number) => Promise<void>;
/**
* Async pool for concurrent iteration with concurrency limit
* @example
* ```
* for await (const ms of asyncPool(2, [1000, 5000, 3000, 2000], ms => sleep(ms))) {
* console.log(ms);
* }
* ```
* @param concurrency
* @param iterable
* @param iterator_fn
*/
declare function asyncPool<T>(concurrency: number, iterable: T[], iterator_fn: (x: T, xs: T[]) => any): AsyncGenerator<any, void, unknown>;
declare const flow_asyncPool: typeof asyncPool;
declare const flow_debounce: typeof debounce;
declare const flow_sleep: typeof sleep;
declare const flow_throttle: typeof throttle;
declare namespace flow {
export { flow_asyncPool as asyncPool, flow_debounce as debounce, flow_sleep as sleep, flow_throttle as throttle };
}
/**
* Randomly pick an item from an array.
* @param xs
* @returns
*/
declare const item: <T>(xs: T[]) => T;
type RandProps = {
min?: number;
max?: number;
};
/**
* Generate a random number (supposedly more random than v1)
* @param props
* @returns
*/
declare const num: (props?: RandProps) => number;
/**
* The Fisher-Yates shuffle is the most efficient algorithm for that purpose.
* @param xs
* @returns
*/
declare const shuffle: <T>(xs: T[]) => T[];
/**
* Randomly return true or false.
* @returns
*/
declare const coinFlip: () => boolean;
/**
* Generate a random date.
* 10000000000 keeps the date to within the current year.
* The more 0s, the greater the range.
* @returns
*/
declare const date: () => Date;
/**
* Generate a random hex color.
* @returns
*/
declare const hexColor: () => string;
declare const random_coinFlip: typeof coinFlip;
declare const random_date: typeof date;
declare const random_hexColor: typeof hexColor;
declare const random_item: typeof item;
declare const random_num: typeof num;
declare const random_shuffle: typeof shuffle;
declare namespace random {
export { random_coinFlip as coinFlip, random_date as date, random_hexColor as hexColor, random_item as item, random_num as num, random_shuffle as shuffle };
}
export { dict as d, flow as f, int as i, list as l, money as m, random as r, str as s, time as t };