minutool
v1.0.8
Published
A collection of utility functions for time, string, object and more
Downloads
891
Maintainers
Readme
minutool
A lightweight collection of utility functions for JavaScript/TypeScript projects.
Installation
npm install minutoolor
yarn add minutoolUsage
import { formatDate, capitalize, deepClone } from 'minutool'
// Time utilities
const now = new Date()
console.log(formatDate(now, 'YYYY-MM-DD')) // '2026-03-10'
// String utilities
console.log(capitalize('hello')) // 'Hello'
// Object utilities
const obj = { a: 1, b: { c: 2 } }
const cloned = deepClone(obj)API Reference
Time Utilities
Constants:
YEAR_NOW- Current yearMONTH_NOW- Current month (1-12)DATE_NOW- Current day of monthONE_MINUTE- Milliseconds in one minutooleONE_HOUR- Milliseconds in one hourONE_DAY- Milliseconds in one dayONE_WEEK- Milliseconds in one weekONE_MONTH30- Milliseconds in 30 daysONE_MONTH31- Milliseconds in 31 daysONE_YEAR365- Milliseconds in 365 daysONE_YEAR366- Milliseconds in 366 daysDAY_SUNDAY- Sunday constant (0)DAY_MONDAY- Monday constant (1)DAY_TUESDAY- Tuesday constant (2)DAY_WEDNESDAY- Wednesday constant (3)DAY_THURSDAY- Thursday constant (4)DAY_FRIDAY- Friday constant (5)DAY_SATURDAY- Saturday constant (6)MONTH_NAMES_CN- Chinese month names arrayMONTH_NAMES_SHORT_CN- Short Chinese month names arrayWEEK_DAY_NAMES_SHORT_CN- Short Chinese weekday names arrayWEEK_DAY_NAMES_CN- Chinese weekday names array
Functions:
formatDate(format: string, date?: Date | number | string | null): string- Format datecountDown(timeout: number, tickFunc?: Function, onFinish?: Function)- Countdown timermsToHMS(ms: number)- Convert milliseconds to hours/minutooles/seconds
String Utilities
Constants:
TRIM_BOTH- Trim both sides constantTRIM_LEFT- Trim left side constantTRIM_RIGHT- Trim right side constant
Functions:
capitalize(str: string): string- Capitalize first lettercamelCase(str: string): string- Convert to camelCasekebabCase(str: string): string- Convert to kebab-casetruncate(str: string, length: number, suffix?: string): string- Truncate stringtrim(str: string, chars?: string, dir?: number): string- Trim stringstripSlashes(str: string): string- Remove slashescutString(str: string, len: number, eclipse_text?: string): string- Cut string with ellipsisextract(es_template: string, params: Record<string, any>): string- Extract with templateregQuote(str: string): string- Escape regex special charactersutf8Decode(srcStr: string): string- Decode UTF-8 stringisJSON(json: string): boolean- Check if string is valid JSONutf8Encode(srcStr: string): string- Encode string to UTF-8getUTF8StrLen(str: string): number- Get UTF-8 string byte lengthrandomString(length?: number, sourceStr?: string): string- Generate random stringrandomWords(count?: number, letterMax?: number): string- Generate random wordsstrToPascalCase(str: string, capitalize_first?: boolean): string- Convert to PascalCase
Object Utilities
Functions:
deepClone<T>(obj: T): T- Deep clone objectisEmptyObject(obj: object): boolean- Check if object is emptyobjectKeyMapping(obj: Record<string, any>, mapping: Record<string, string>): Record<string, any>- Map object keysobjectGet<T>(obj: any, path: string, defaultValue?: T): T- Get value by pathobjectSet(obj: any, path: string, value: any): void- Set value by pathobjectMerge<T>(target: T, ...sources: Partial<T>[]): T- Deep merge objects
Array Utilities
Functions:
arrayColumn<T>(arr: T[], col_name: keyof T): any[]- Extract column from array of objectsarrayIndex<T>(arr: T[], val: T): string | null- Find index of valuearrayDistinct<T>(arr: T[]): T[]- Remove duplicatesarrayGroup<T>(arr: T[], by_key: keyof T, limit?: boolean): Record<string, T[] | T>- Group array by keyarraySortByKey<T>(obj: T): T- Sort object by keysarrayChunk<T>(list: T[], size: number): T[][]- Split array into chunks
Math Utilities
Constants:
GOLDEN_RATIO- Golden ratio constant
Functions:
between(val: number, min: number, max: number, includeEqual?: boolean): boolean- Check if value is between rangerandomInt(min: number, max: number): number- Generate random integerround(num: number, precision?: number): number- Round number to precision
Base64 Utilities
Functions:
base64Decode(text: string): string- Decode base64 stringbase64UrlSafeEncode(text: string): string- URL-safe base64 encodeBase64Encode(text: string): string- Encode to base64blobToBase64(blob: Blob): Promise<unknown>- Convert Blob to base64
Browser Utilities
Functions:
enterFullScreen(element: any): Promise<void>- Enter fullscreen modeexitFullScreen(): void- Exit fullscreen modetoggleFullScreen(element: any): Promise<unknown>- Toggle fullscreenisInFullScreen(): boolean- Check if in fullscreendetectLanguage(supportedLngs: string[]): string- Detect browser language
Cookie Utilities
Functions:
setCookie(name: string, value: string, days: number, path?: string): void- Set cookiegetCookie(name: string): string | null- Get cookie valuedeleteCookie(name: string): void- Delete cookie
DOM Utilities
Functions:
hide(dom: HTMLElement | string): void- Hide elementshow(dom: HTMLElement | string): void- Show elementremove(dom: HTMLElement | string): Node | null- Remove elementdisabled(el: HTMLElement | string, disabledClass?: string): void- Disable elementenabled(el: HTMLElement | string, disabledClass?: string): void- Enable elementtoggleDisabled(el: HTMLElement | string, disabledClass?: string, forceEnabled?: boolean | null): void- Toggle disabled statelockElementInteraction(el: HTMLElement | string, payload: Function): void- Lock element interactionnodeIndex(node: HTMLElement): number- Get node indexfindAll(selector: string | HTMLElement, parent?: Document | HTMLElement): HTMLElement[]- Find all elementsfindOne(selector: string | HTMLElement, parent?: Document | HTMLElement): HTMLElement- Find one elementgetNodeXPath(el: HTMLElement | null): string | null- Get element XPathonDomTreeChange(dom: HTMLElement, callback: Function, includeElementChanged?: boolean): void- Watch DOM tree changesmutationEffective(dom: HTMLElement, option: MutationObserverInit, payload: Function, minInterval?: number): void- Mutation observer with throttlekeepRectInContainer(rect: Dimension, container: Dimension): Dimension- Keep rectangle in containerrectAssoc(rect1: Dimension, rect2: Dimension): boolean- Check if rectangles overlaploadCss(file: string, forceReload?: boolean): Promise<void>- Load CSS fileloadScript(src: string, forceReload?: boolean): Promise<void>- Load script filegetDomDimension(dom: HTMLElement): { width: number; height: number }- Get element dimensionsinsertStyleSheet(styleSheetStr: string, id?: string, doc?: Document): HTMLStyleElement | null- Insert stylesheetrectInLayout(rect: Dimension, layout: Dimension): boolean- Check if rect is in layoutcreateDomByHtml(html: string, parentNode?: HTMLElement | null): Node | Node[]- Create DOM from HTMLisFocusable(el: HTMLElement): boolean- Check if element is focusablegetBoundingClientRect(el: HTMLElement, autoFixInvisible?: boolean): RectObject- Get element bounding rect
HTML Utilities
Constants:
BLOCK_TAGS- Array of block-level HTML tagsPAIR_TAGS- Array of paired HTML tagsSELF_CLOSING_TAGS- Array of self-closing HTML tagsREMOVABLE_TAGS- Array of removable HTML tags
Functions:
html2Text(html: string): string- Convert HTML to plain textcssSelectorEscape(str: string): string- Escape CSS selectorentityToString(entity: string): string- Convert HTML entity to stringdecodeHTMLEntities(str: string): string- Decode HTML entitiesbuildHtmlHidden(maps: Record<string, any>): string- Build hidden input fieldsescapeHtml(str: string, tabSize?: number, allowLineBreaker?: boolean): string- Escape HTMLunescapeHtml(html: string): string- Unescape HTMLescapeAttr(s: string, preserveCR?: string): string- Escape HTML attributestringToEntity(str: string, radix?: number): string- Convert string to HTML entityhighlightText(text: string, kw: string, replaceTpl?: string): string- Highlight text
Image Utilities
Functions:
imgToBase64(img: HTMLImageElement): string | null- Convert image to base64srcToBase64(src: string): Promise<unknown>- Convert image src to base64
MD5 Utility
Functions:
MD5(string: string, key?: string, raw?: boolean): string- Generate MD5 hash
MIME Utilities
Constants:
MIME_BINARY_DEFAULT- Default binary MIME typeMIME_EXTENSION_MAP- Map of file extensions to MIME types
General Utilities
Functions:
guid(prefix?: string): string- Generate unique IDthrottle(fn: Function, intervalMiSec: number): Function- Throttle functionthrottleEffect(fn: Function, intervalMiSec: number): Function- Throttle with effectdebounce(fn: Function, intervalMiSec: number): Function- Debounce functionisPromise(obj: any): boolean- Check if value is PromiseisObject(item: any): boolean- Check if value is objectisFunction(value: any): boolean- Check if value is functionisURL(str: string): boolean- Check if string is valid URLprintStack(): void- Print call stack
File Utilities
Functions:
sanitizeFileName(name: string): string- Sanitize file nameblobToDataURL(blob: Blob): Promise<string>- Convert Blob to data URLfileToBase64DataURL(file: File | Blob | string): Promise<string>- Convert file to base64 data URLdownloadFile(uri: string, fileName: string): void- Download file
License
MIT
