UNPKG

js-cool

Version:

Collection of common JavaScript / TypeScript utilities

1,800 lines (1,657 loc) 60.4 kB
import { default as awaitTo } from 'await-to-done'; import { download } from 'use-downloads'; import { default as loadSource } from 'load-source'; import { default as mountCss } from 'mount-css'; import { default as mountImg } from 'mount-image'; import { default as mountJs } from 'mount-script'; import { default as mountStyle } from 'mount-style'; /** * addEvent() event delegate, supports multiple delegates * * @since 1.0.2 * @param element - js dom object * @param type - The event type. No need to add on * @param handler - callback method */ export declare function addEvent(element: AnyObject, type: string, handler: AnyFunction): void; export declare namespace addEvent { var guid: number; } /** * Returns true if the provided predicate function returns true for all elements in a set, otherwise it returns false. * * @example * ```js * all([4, 2, 3], x => x > 1) * // true * ``` * @since 1.0.9 * @param arr - the target array * @param fn - the judgment method * @returns - the result of the judgment */ export declare const all: <T = unknown>(arr: T[], fn: AnyFunction) => boolean; /** * Returns true if the provided predicate function returns true for at least one element of a set, otherwise it returns false. * * @example * ```js * any([0, 1, 2, 0], x => x >= 2) * // true * ``` * @since 1.0.9 * @param arr - the target array * @param fn - the judgment method * @returns - the result of the judgment */ export declare const any: <T = unknown>(arr: T[], fn: AnyFunction) => boolean; export declare interface AnyFunction extends AnyObject { (...args: any[]): any; } export declare type AnyObject = Record<string, any>; /** * Get the APP version from navigator.userAgent, support 'x.x.x' & 'x.x.x-tagname.x' * * @example * ```js * // navigator.userAgent => '5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 AppName/1.0.0-beta.8' * appVersion('Chrome') // 114.0.0.0 * appVersion('Safari') // 537.36 * appVersion('appname', false) // null * appVersion('appname') // 1.0.0-beta.8 * ``` * @since 5.1.0 * @param appName - app name * @param ua - ua or any ua like string, allowed to be undefined, default is navigator.userAgent * @param ignoreCase - whether to ignore case * @return string|null */ export declare function appVersion(appName: string): string | null; export declare function appVersion(appName: string, ua: string): string | null; export declare function appVersion(appName: string, ua: boolean): string | null; export declare function appVersion(appName: string, ua: string, ignoreCase: boolean): string | null; /** * arrayBuffer to base64 * * @example * ```js * arrayBufferToBase64(arrayBuffer, 'image/png') * // data:image/png;base64,xxxxxxxxxxxx * * arrayBufferToBase64(arrayBuffer) * // xxxxxxxxxxxx * ``` * @since 5.13.0 * @param input - arrayBuffer * @param mime - image mime, eq: image/png * @returns - base64 */ export declare function arrayBufferToBase64(input: ArrayBuffer, mime?: string): string; /** * arrayBuffer to blob * * @since 5.13.0 * @param input - arrayBuffer * @param mime - image mime, default: image/png * @returns - blob */ export declare function arrayBufferToBlob(input: ArrayBuffer, mime?: string): Blob; export declare interface ArrayOne<T> { 0: T; } export declare type ArrayOneMore<T> = ArrayOne<T> & Array<T>; /** * Converts a two-dimensional array to a comma-separated string of values (CSV). * * @example * ```js * arrayToCSV([['a', 'b'], ['c', 'd']]) * // '"a", "b" \n "c", "d"' * * arrayToCSV([['a', 'b'], ['c', 'd']], ';') * // '"a"; "b"\n "c"; "d"' * * arrayToCSV([['a', '"b" great'], ['c', 3.1415]]) * // '"a", """b"" great"\n "c",3.1415' * ``` * @since 1.0.9 * @param data - json data * @param delimiter - delimiter, default ',' * @returns CSV data */ export declare const arrayToCSV: <T extends unknown[][]>(arr: T, delimiter?: string) => string; export declare type ArrayTwoMore<T> = { 0: T; 1: T; } & Array<T>; export { awaitTo } /** * base64 to arrayBuffer * * @since 5.13.0 * @param input - base64 string * @returns - arrayBuffer */ export declare function base64ToArrayBuffer(input: string): Uint8Array<ArrayBuffer> | Buffer<ArrayBuffer>; /** * base64 to blob * * @since 5.13.0 * @param input - base64 string * @returns - blob */ export declare function base64ToBlob(input: string): Blob; /** * base64 to file * * @since 5.13.0 * @param input - base64 string * @param fileName - file name * @returns - the BASE64 encoding */ export declare function base64ToFile(input: string, fileName: string): File; /** * blob to arrayBuffer * * @since 5.13.0 * @param input - blob data * @returns - arrayBuffer */ export declare function blobToArrayBuffer(input: Blob): Promise<ArrayBuffer | null>; /** * blob to base64 * * @since 5.13.0 * @param input - blob data * @returns - base64 string */ export declare function blobToBase64(input: Blob): Promise<string | null>; /** * blob to blobUrl * * @since 5.13.0 * @param input - blob data * @returns - blobUrl */ export declare function blobToUrl(input: Blob): string; export declare interface BrowserVersion { name: 'Safari' | 'Chrome' | 'IE' | 'Edge' | 'Firefox' | 'Firefox Focus' | 'Chromium' | 'Opera' | 'Vivaldi' | 'Yandex' | 'Arora' | 'Lunascape' | 'QupZilla' | 'Coc Coc' | 'Kindle' | 'Iceweasel' | 'Konqueror' | 'Iceape' | 'SeaMonkey' | 'Epiphany' | '360' | '360SE' | '360EE' | 'Maxthon' | 'QQBrowser' | 'QQ' | 'Baidu' | 'UC' | 'Sogou' | 'Liebao' | 'LBBROWSER' | '2345Explorer' | '115Browser' | 'TheWorld' | 'XiaoMi' | 'Vivo' | 'Quark' | 'Qiyu' | 'Wechat' | 'WechatWork' | 'Taobao' | 'Alipay' | 'Weibo' | 'Douban' | 'Suning' | 'iQiYi' | 'DingTalk' | 'Huawei'; version: string; } /** * Get the browser name and version * * @example * ``` * // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Ap…KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 * browserVersion() // \{ name: 'Chrome', version: '114.0.0.0' \} * ``` * @since 5.2.0 * @param ua - ua or any ua like string, allowed to be undefined, default is navigator.userAgent * @return BrowserVersion|null */ export declare function browserVersion(ua?: string): BrowserVersion | null; /** * Converts humped strings to -spaced and all lowercase Dash pattern * * @since 1.0.1 * @param string - the string to be converted * @returns - the converted string */ export declare function camel2Dash(string: string): string; /** * Data cleaning methods * * @since 1.0.2 * @param data - the object to be cleaned, must be passed * @param map - the data queue to be cleaned, can be passed as array or object * @param map - * @param nullFix - * @param map - * @param nullFix - * @param nullFix - optional, the value returned if there is no corresponding property, the default does not return the property * @returns - the cleaned object */ export declare function cleanData(data: any, map: any[] | AnyObject, nullFix?: any): any; /** * Remove all attributes of HTML tags * * @since 1.0.1 * @param string - pass in the string * @returns newString */ export declare function clearAttr(string: string): string; /** * Removing HTML tags * * @since 1.0.1 * @param string - string with html tags * @returns newString */ export declare function clearHtml(string: string): string; /** * The client method returns a browser judgment result: `{ ANDROID: true, GECKO: true, GLSH_APP: false, IE: false, IOS: false, IPAD: false, IPHONE: false, MOBILE: true, MOBILEDEVICE. true, OPERA: false, QQ: false, QQBROWSER: false, TRIDENT: false, WEBKIT: true, WEIXIN: false }` * * @deprecated Will be refactored for the next major release * @since 1.0.1 * @param name - optional, e.g. pass in MicroMessenger to return whether it is the built-in browser of Weixin * @param userAgent - optional, pass in a custom ua, default takes the browser's navigator.userAgent * @returns - the common ua match table, if name is passed, then returns whether the terminal matches true/false */ export declare const client: (name?: string, userAgent?: string) => boolean | { IE: boolean; GECKO: boolean; WEBKIT: boolean; OPERA: boolean; TRIDENT: boolean; MOBILE: boolean; IOS: boolean; ANDROID: boolean; IPHONE: boolean; IPAD: boolean; QQBROWSER: boolean; WEIXIN: boolean; QQ: RegExpMatchArray | null; }; /** * deep clone (Buffer, Promise, Set, Map are not supported) * * @example * ```js * const source = { a: 100, reg: /\d+/g, arr: [1, 2] } * const res = clone(source) * // { a: 100, reg: /\d+/g, arr: [1, 2] } * ``` * @since 5.15.0 * @param parent - source object * @returns - new object */ export declare function clone<T = any>(parent: T): T; /** * Version number size comparison, tag version: rc \> beta \> alpha \> other * * @example * ```js * compareVersion('1.11.0', '1.9.9') * // => 1: 1=Version 1.11.0 is newer than 1.9.9 * * compareVersion('1.11.0', '1.11.0') * // => 0: 0=Versions 1.11.0 and 1.11.0 are the same * * compareVersion('1.11.0', '1.99.0') * // => -1: -1=Version 1.11.0 is older than 1.99.0 * * compareVersion('1.0.0.0.0.10', '1.0') * // => -1 * * // compare tag version: rc > beta > alpha > other * compareVersion('1.11.0', '1.11.0-beta.1') * // => -1 * * compareVersion('1.11.0-beta.1', '1.11.0') * // => -1 * * compareVersion('1.11.0-beta.10', '1.11.0-beta.10') * // => 0 * * compareVersion('1.11.0-alpha.10', '1.11.0-beta.1') * // => -1 * * compareVersion('1.11.0-alpha.10', '1.11.0-rc.1') * // => -1 * * compareVersion('1.11.0-tag.10', '1.11.0-alpha.1') * // => -1 * * compareVersion('1.11.0-tag.10', '1.11.0-tag.1') * // => 1 * * compareVersion('1.11.0-release.10', '1.11.0-tag.1') * // => 1 * ``` * @since 4.7.0 * @param input - input version * @param compare - compare version * @return 1/0/-1 */ export declare function compareVersion(input: string, compare: string): 0 | 1 | -1; /** * Find the complement of multiple arrays * * @example * ```js * complement([1, 2], [2, '33'], [2]) // [1, '33'] * ``` * @since 2.2.1 * @param args - arguments * @returns array */ export declare function complement<T = unknown>(...args: T[][]): T[]; /** * Whether the array contains the specified element * * @example * ```js * contains([1, 2], 2) // true * contains([1, 2], 3) // false * ``` * @since 2.2.1 * @param arr - the target array * @param item - the target to find * @returns boolean */ export declare function contains(arr: any[], item: any): boolean; /** * copy to clipboard * * @since 5.0.0 * @param value - any target * @returns - target is Object */ export declare function copy(value: any): boolean | undefined; /** * Converts a comma-separated string of values (CSV) to a 2D array. * * @example * ```js * CSVToArray('a,b\\nc,d') * // `[['a','b'],['c','d']]`. * * CSVToArray('a;b\\\nc;d', ';') * // `[['a','b'],['c','d']]`. * * CSVToArray('col1,col2\\\na,b\\\nc,d', ',', true) * // `[['a','b'],['c','d']]`. * ``` * @since 1.0.9 * @param data - csv data * @param delimiter - separator, default ',' * @param omitFirstRow - the first row is the table header data, default false * @returns array */ export declare const CSVToArray: (data: string, delimiter?: string, omitFirstRow?: boolean) => string[][]; /** * Converts a comma-separated string of values (CSV) to an array of 2D objects. The first line of the string is used as the header line. * * @example * ```js * CSVToJSON('col1,col2\\na,b\\\nc,d') * // `[{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]`. * * CSVToJSON('col1;col2\\\na;b\\\nc;d', ';') * // `[{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]`. * ``` * @since 1.0.9 * @param data - csv data * @param delimiter - delimiter, default ',' * @returns - json */ export declare function CSVToJSON(data: string, delimiter?: string): any[]; /** * Intercept string, Chinese counts as 2 bytes * * @since 1.0.1 * @param str - the string to be intercepted * @param len - * @param hasDot - * @returns - the intercepted string */ export declare function cutCHSString(str: string, len?: number, hasDot?: boolean): string; /** * Converts -spaced and all lowercase Dash patterns to humped strings * * @since 1.0.1 * @param string - the string to be converted * @returns - the converted string */ export declare function dash2Camel(string: string): string; /** * base64 decoding * * @since 1.0.1 * @param input - the string to be decoded * @returns decoded string */ export declare function decodeBase64(input: string): string; /** * Decoding Utf8 * * @since 1.0.1 * @param input - the string to be decoded * @returns decoded string */ export declare function decodeUtf8(utftext: string): string; declare const _default: { version: string; download: typeof download; RGBToHex: (r: number, g: number, b: number) => string; addEvent: typeof addEvent; all: <T = unknown>(arr: T[], fn: AnyFunction) => boolean; any: <T = unknown>(arr: T[], fn: AnyFunction) => boolean; getCache: typeof getCache; setCache: typeof setCache; delCache: typeof delCache; getSession: typeof getSession; setSession: typeof setSession; delSession: typeof delSession; getCookie: typeof getCookie; getCookies: typeof getCookies; setCookie: typeof setCookie; delCookie: typeof delCookie; camel2Dash: typeof camel2Dash; cleanData: typeof cleanData; clearAttr: typeof clearAttr; clearHtml: typeof clearHtml; escape: typeof escape_2; unescape: typeof unescape_2; client: (name?: string, userAgent?: string) => boolean | { IE: boolean; GECKO: boolean; WEBKIT: boolean; OPERA: boolean; TRIDENT: boolean; MOBILE: boolean; IOS: boolean; ANDROID: boolean; IPHONE: boolean; IPAD: boolean; QQBROWSER: boolean; WEIXIN: boolean; QQ: RegExpMatchArray | null; }; complement: typeof complement; contains: typeof contains; CSVToArray: (data: string, delimiter?: string, omitFirstRow?: boolean) => string[][]; arrayToCSV: <T extends unknown[][]>(arr: T, delimiter?: string) => string; CSVToJSON: typeof CSVToJSON; JSONToCSV: (arr: any[], columns: any[], delimiter?: string) => string; cutCHSString: typeof cutCHSString; dash2Camel: typeof dash2Camel; decodeBase64: typeof decodeBase64; decodeUtf8: typeof decodeUtf8; delay: typeof delay; encodeBase64: typeof encodeBase64; encodeUtf8: typeof encodeUtf8; extend: typeof extend; clone: typeof clone; fillIPv6: typeof fillIPv6; fixNumber: typeof fixNumber; mapTemplate: typeof mapTemplate; getAppVersion: typeof getAppVersion; appVersion: typeof appVersion; getCHSLength: typeof getCHSLength; getDirParam: typeof getDirParam; compareVersion: typeof compareVersion; getNumber: typeof getNumber; getOsVersion: typeof getOsVersion; osVersion: typeof osVersion; browserVersion: typeof browserVersion; getQueryParam: typeof getQueryParam; getQueryParams: typeof getQueryParams; getProperty: typeof getProperty; randomColor: typeof randomColor; randomNumber: typeof randomNumber; randomNumbers: typeof randomNumbers; randomString: typeof randomString; shuffle: typeof shuffle; fingerprint: typeof fingerprint; getScrollPosition: typeof getScrollPosition; getType: typeof getType; getFileType: typeof getFileType; sorter: typeof sorter; sortPinyin: typeof sortPinyin; parseUrlParam: typeof parseUrlParam; spliceUrlParam: typeof spliceUrlParam; safeParse: typeof safeParse; safeStringify: typeof safeStringify; getUrlParam: typeof getUrlParam; getUrlParams: typeof getUrlParams; intersect: typeof intersect; isDigitals: typeof isDigitals; isExitsFunction: typeof isExitsFunction; isExitsVariable: typeof isExitsVariable; isEqual: typeof isEqual; isWindow: typeof isWindow; isObject: typeof isObject; isDate: typeof isDate; isRegExp: typeof isRegExp; isArray: typeof isArray; isIterable: typeof isIterable; isPlainObject: typeof isPlainObject; isDarkMode: typeof isDarkMode; inBrowser: boolean; inNodeJs: boolean; isNumberBrowser: typeof isNumberBrowser; minus: typeof minus; nextIndex: typeof nextIndex; nextVersion: typeof nextVersion; punctualTimer: typeof punctualTimer; promiseFactory: typeof promiseFactory; waiting: (milliseconds: number, throwOnTimeout?: boolean) => Promise<void>; awaitTo: typeof awaitTo; arrayBufferToBase64: typeof arrayBufferToBase64; arrayBufferToBlob: typeof arrayBufferToBlob; base64ToArrayBuffer: typeof base64ToArrayBuffer; base64ToBlob: typeof base64ToBlob; base64ToFile: typeof base64ToFile; blobToArrayBuffer: typeof blobToArrayBuffer; blobToBase64: typeof blobToBase64; blobToUrl: typeof blobToUrl; fileToBase64: typeof fileToBase64; svgToBlob: typeof svgToBlob; urlToBlob: typeof urlToBlob; openUrl: typeof openUrl; copy: typeof copy; pattern: { any: RegExp; number: RegExp; string: RegExp; postcode: RegExp; url: RegExp; username: RegExp; float: RegExp; email: RegExp; mobile: RegExp; chinese: RegExp; tel: RegExp; qq: RegExp; pass: RegExp; json: RegExp; arrjson: RegExp; array: RegExp; isjson: RegExp; textarea: RegExp; mac: RegExp; ip4: RegExp; ip4_pri: RegExp; }; removeEvent: typeof removeEvent; searchObject: typeof searchObject; setProperty: typeof setProperty; stopBubble: typeof stopBubble; stopDefault: typeof stopDefault; toThousands: typeof toThousands; trim: typeof trim; union: typeof union; unique: typeof unique; upperFirst: typeof upperFirst; uuid: () => string; windowSize: typeof windowSize; loadSource: typeof loadSource; mountCss: typeof mountCss; mountImg: typeof mountImg; mountJs: typeof mountJs; mountStyle: typeof mountStyle; preloader: typeof preloader; }; export default _default; /** * debounce & throttle * * @since 1.0.2 * @returns class */ export declare function delay(): { map: any; register(id: string, fn: AnyFunction, time: number, boo: boolean): void; destroy(id: string): void; }; /** * Delete localStorage * * @since 1.0.2 * @param name - name */ export declare function delCache(name: string): void; /** * Delete cookie * * @since 1.0.2 * @param name - cookie name */ export declare function delCookie(name: string): void; /** * Delete sessionStorage * * @since 1.0.2 * @param name - name */ export declare function delSession(name: string): void; export declare interface DirParamType { path?: string[]; host?: string; } export { download } /** * String, number to base64 * * @since 1.0.1 * @param input - the string to be encoded * @returns - the BASE64 encoding */ export declare function encodeBase64(input: string): string; /** * Encoding Utf8 * * @since 1.0.1 * @param input - the string to be encoded * @returns - the UTF-8 encoding */ export declare function encodeUtf8(string: string): string; /** * Escaping HTML Special Characters * * @example * ```js * escape('<div>test<br />string</div>') * // '&lt;div&gt;test&lt;br /&gt;string&lt;/div&gt;' * ``` * @since 5.5.0 * @param string - string with html tags * @returns - newString */ declare function escape_2(string: string): string; export { escape_2 as escape } /** * deep copy & merge objects * * @since 1.0.2 * @param target - boolean | ExtendData * @param args - ArrayOneMore<ExtendData> */ export declare function extend(target: ExtendObjectData, ...args: ArrayOneMore<ExtendObjectData>): ExtendObjectData; export declare function extend(target: boolean, ...args: ArrayOneMore<ExtendObjectData>): ExtendObjectData; export declare function extend(target: ExtendArrayData, ...args: ArrayOneMore<ExtendArrayData>): ExtendArrayData; export declare function extend(target: boolean, ...args: ArrayOneMore<ExtendArrayData>): ExtendArrayData; export declare type ExtendArrayData = any[]; export declare type ExtendData = ExtendArrayData | ExtendObjectData; export declare type ExtendObjectData = Record<string, any>; /** * file to base64 * * @since 5.13.0 * @param input - file data * @returns - base64 string */ export declare function fileToBase64(input: File): Promise<string | null>; /** * Read full IPv6 * * @example * ```js * fillIPv6('2409:8005:800::2') * // '2409:8005:0800:0000:0000:0000:0000:0002' * * fillIPv6('2409:8005:800::1c') * // '2409:8005:0800:0000:0000:0000:0000:001c' * ``` * @since 2.2.2 * @returns - string */ export declare function fillIPv6(ip: string): string; /** * Generating Browser Fingerprints * * @since 5.2.0 * @param domain - key string, default: location.host * @returns - fingerprint */ export declare function fingerprint(domain?: string): string | null; /** * Intercept the decimal places, do not fill in the missing 0 * * @example * ```js * fixNumber('100.888') * // 100.88 * * fixNumber('100.8', 2) * // 100.8 * * fixNumber('100.8888', 3) * // 100.888 * ``` * @since 1.0.2 * @param number - the number of digits to be processed, required * @param n - the number of decimal places to keep, default is 2 * @returns - the new number */ export declare function fixNumber(number: string | number, n?: number): number; /** * Get the APP version number * * @deprecated please use 'appVersion' instead * @since 1.0.1 * @param appName - app name * @param withApp - whether to bring the name * @param userAgent - ua, allowed to be undefined, default is navigator.userAgent * @return null/true/false */ export declare function getAppVersion(appName: string, withApp?: boolean, userAgent?: string): string | boolean | null; /** * Get the cache, if the deposited is Object, the retrieved is also Object, no need to convert again * * @example * ```js * const data1 = 100 * const data2 = { a: 10 } * const data3 = null * * setCache('data1', data1) * setCache('data2', data2) * setCache('data3', data3) * * getCache('data1') // 100 * getCache('data2') // {a:10} * getCache('data3') // null * * getCache('data4') // null * ``` * @since 1.0.2 * @param name - cache name * @returns - data, if it's an object, it's also an object */ export declare function getCache(name: string): any; /** * Get the length of the text, Chinese counts as 2 bytes * * @example * ```js * getCHSLength('测试') * // 2 * ``` * @since 1.0.1 * @param str - string * @returns - length */ export declare function getCHSLength(str: string): number; /** * Read cookie by name * * @example * ```js * getCookie('data1') * // 100 * ``` * @since 1.0.2 * @param name - cookie name * @returns - the cookie string */ export declare function getCookie(name: string): any; /** * Read all cookies * * @example * ```js * getCookies() * // \{ token: 'xxx', name: 'saqqdy' \} * ``` * @since 5.6.0 * @returns - the cookie values */ export declare function getCookies(): Record<string, string>; /** * Get directory form URL parameters * * @deprecated It will be refactored and renamed getDirParams in the next major release. * @since 1.0.1 * @param url - pass in the url address * @returns - parameter object */ export declare function getDirParam(url: string): DirParamType; /** * Determine file type based on link suffix * * @example * ```js * getFileType('/name.png') * // { "suffix": "png", "type": "image" } * * getFileType('/name.PDF') * // { "suffix": "pdf", "type": "pdf" } * * getFileType('/name.xyz') * // { "suffix": "xyz", "type": "other" } * ``` * @since 5.11.0 * @param url - file url * @returns result */ export declare function getFileType(url: string): { suffix: string; type: "audio" | "video" | "image" | "other" | "word" | "txt" | "excel" | "pdf" | "ppt" | "zip"; }; /** * Get the number in the string * * @example * ```js * getNumber('Chrome123.33') * // '123.33'. * * getNumber('234test.88') * // '234.88'. * ``` * @since 1.0.1 * @param string - pass in a string with a number * @returns - a pure numeric string */ export declare function getNumber(string: string): string; /** * Get the phone system version * * @example * ``` * getOsVersion('iPhone') * // '13.2.3' * * getOsVersion('iPhone', true) * // 'iPhone/13.2.3' * ``` * @deprecated please use 'osVersion' instead * @since 1.0.1 * @param osName - system type string Android, iPod, iWatch or iPhone * @param withOS - whether to bring the name * @param userAgent - ua, allowed to be undefined, default takes navigator.userAgent * @return - null/true/false */ export declare function getOsVersion(osName: string, withOS?: boolean, userAgent?: string): string | boolean | null; /** * Get array, object property values based on path string * * @example * ```js * const target = { * a: 1, * b: [{ * c: 2 * d: NaN * }] * } * getProperty(target, 'a') // 1 * getProperty(target, 'd', 100) // 100 * getProperty(target, 'b[0].c') // 2 * getProperty(target, 'b[0].d', 100) // 100 * getProperty(target, () => 'a') // 1 * ``` * @since 2.2.4 * @param target - target array, object * @param prop - query target, can pass function * @param defaultValue - default value * @returns result */ export declare function getProperty<T extends Record<string, any>>(target: T, prop: string | { (): string; }, defaultValue?: any): any; export declare function getProperty<T extends Array<any>>(target: T, prop: string | { (): string; }, defaultValue?: any): any; /** * Get a single query parameter (behind "#") * * @example * ```js * getQueryParam('key1') * // key1 => xxx * * getQueryParam('key1', 'https://test.com?key1=100#/home?key1=200') * // key1 => 200 * ``` * @since 5.0.0 * @param key - key name * @param url - pass in the url string * @returns - result */ export declare function getQueryParam(key: string): string | undefined; export declare function getQueryParam(key: string, url: string): string | undefined; /** * Get all URL parameters (behind "#") * * @example * ```js * getQueryParams('https://test.com?key1=100#/home?key1=200') * // \{"key1":"200"\} * * getQueryParams('https://test.com?key1=100#/home?key1=200', true) * // \{"key1":200\} * * getQueryParams(true) * // \{"key1":200\} * ``` * @since 5.0.0 * @param url - pass in the url string * @param covert - Converts a specific string to a corresponding value (Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2) * @returns - result */ export declare function getQueryParams(url: string): Record<string, string>; export declare function getQueryParams(url: boolean): Record<string, unknown>; export declare function getQueryParams(url: string, covert: boolean): Record<string, unknown>; /** * Get slide to top and bottom return 'top' 'bottom', recommend using limit flow * * @deprecated will be removed in the next major release. * @since 1.0.2 * @returns - position */ export declare function getScrollPosition(): "bottom" | "top" | undefined; /** * Read sessionStorage * * @example * ```js * const data1 = 100 * const data2 = { a: 10 } * const data3 = null * * setSession('data1', data1) * setSession('data2', data2) * setSession('data3', data3) * * getSession('data1') // 100 * getSession('data2') // {a:10} * getSession('data3') // null * * getSession('data4') // null * ``` * @since 1.0.2 * @param name - name * @returns - sessionStorage */ export declare function getSession(name: string): any; /** * Get the target type * * @since 1.0.2 * @param target - target * @returns type */ export declare function getType<T = any>(target: T): "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "window" | "error" | "promise" | "math" | "document" | "navigator" | "global" | "array" | "date" | "regexp" | "null"; /** * Get a single URL parameter (from the "location.search", before "#") * * @example * ```js * getUrlParam('key1') * // key1 => xxx * * getUrlParam('key1', 'https://test.com?key1=100#/home?key1=200') * // key1 => 100 * ``` * @since 5.0.0 * @param key - key name * @param url - pass in the url string * @returns - result */ export declare function getUrlParam(key: string): string | undefined; export declare function getUrlParam(key: string, url: string): string | undefined; /** * Get all URL parameters (from the "location.search", before "#") * * @example * ```js * getUrlParams('https://test.com?key1=100#/home?key1=200') * // \{"key1":"100"\} * * getUrlParams('https://test.com?key1=100#/home?key1=200', true) * // \{"key1":100\} * * getUrlParams(true) * // \{"key1":100\} * ``` * @since 5.0.0 * @param url - pass in the url string * @param covert - Converts a specific string to a corresponding value (Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2) * @returns - result */ export declare function getUrlParams(url: string): Record<string, string>; export declare function getUrlParams(url: boolean): Record<string, unknown>; export declare function getUrlParams(url: string, covert: boolean): Record<string, unknown>; /** * Determine if it is running on the browser side * * @since 4.5.0 * @returns boolean */ export declare const inBrowser: boolean; /** * Determine if it is running on node.js * * @since 5.13.0 * @returns boolean */ export declare const inNodeJs: boolean; /** * Find the intersection of multiple arrays * * @example * ```js * intersect([1, 2], [2, 3, 4], [2, 8], [2, '33']) // [2] * ``` * @since 2.2.1 * @param args - arguments * @returns - new array */ export declare function intersect<T = unknown>(...args: T[][]): T[]; /** * Determine if it is an array * * @example * ```js * isArray([]) // true * ``` * @since 1.0.2 * @param target - any target * @returns - target is Array */ export declare function isArray(target: any): target is any[]; /** * Determine if dark color mode * * @example * ```js * isDarkMode() // true * ``` * @since 5.5.0 * @returns - result */ export declare function isDarkMode(): boolean; /** * Determine if target is Date * * @example * ```js * const now = new Date() * * isDate(now) * // true * ``` * @since 5.15.0 * @param target - any target * @returns - target is Date */ export declare function isDate(target: any): target is Date; /** * Whether or not it is a string consisting of numbers * * @deprecated will be removed in the next major release. * @since 1.0.1 * @param str - the string to be tested * @returns - true/false */ export declare function isDigitals(str: string): boolean; /** * Determine if 2 objects are equal * * @example * ```js * isEqual({ a: 22, b: {} }, { b: {}, a: 22 }) * // true * * isEqual([1, 2], [2, 1]) * // false * * isEqual(NaN, NaN) * // true * ``` * @since 5.12.0 * @param a - source * @param b - compare * @returns - a equals to b */ export declare function isEqual<T, P>(a: T, b: P): boolean; /** * The presence or absence of the specified function * * @example * ```js * isExitsFunction('test') // false * isExitsFunction('console.log') // true * ``` * @since 1.0.1 * @param name - incoming function name * @returns - true/false */ export declare function isExitsFunction(name: string): boolean; /** * The presence or absence of the specified variable * * @example * ```js * isExitsVariable('test') // false * isExitsVariable('window') // true * ``` * @since 1.0.1 * @param name - variable name * @returns - true/false */ export declare function isExitsVariable(name: string): boolean; /** * Determine if it is iterable * * @example * ```js * isIterable([]) // true * ``` * @since 5.7.0 * @param target - any target * @returns - target is Array */ export declare function isIterable<T = any>(target: T | Iterable<T>): target is Iterable<T>; /** * Detect if the client is a 360 browser * * @example * ```js * // 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36 QIHU 360EE' * // true * * // 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36' * // true * ``` * @since 5.22.0 * @param userAgent - ua, allowed to be undefined, default takes navigator.userAgent * @returns - result */ export declare function isNumberBrowser(userAgent?: string): boolean; /** * Determine if target is an object * * @example * ```js * isObject({}) // true * ``` * @since 5.0.0 * @param target - any target * @returns - target is Object */ export declare function isObject(target: any): target is Object; /** * Determine if target is an plain object * * @example * ```js * isPlainObject({}) // true * isPlainObject(window) // false * ``` * @since 5.0.0 * @param target - any target * @returns - target is plain Object */ export declare function isPlainObject(target: unknown): target is PlainObject; /** * Determine if target is RegExp * * @example * ```js * isRegExp(/\d/) // true * ``` * @since 5.15.0 * @param target - any target * @returns - target is RegExp */ export declare function isRegExp(target: any): target is RegExp; /** * Determine if target is an window object * * @example * ```js * isWindow({}) // false * isWindow(window) // true * ``` * @since 5.0.0 * @param target - any * @returns - target is Window */ export declare function isWindow(target: any): target is Window; export declare interface JSONArray extends Array<JSONValue> { } /** * Converts an array of objects to a comma-separated value (CSV) string containing only the specified columns. * * @example * ```js * JSONToCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']) * // 'a,b\n "1", "2"\n "3", "4"\n "6",""\n"", "7"' * * JSONToCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';') * // 'a;b\n "1"; "2"\n "3"; "4"\n "6";""\n""; "7"' * ``` * @since 1.0.9 * @param data - json data * @param columns - the specified columns * @param delimiter - delimiter, default ',' * @returns - CSV data */ export declare const JSONToCSV: (arr: any[], columns: any[], delimiter?: string) => string; export declare type JSONValue = Primitive | PlainObject | JSONArray; export { loadSource } /** * Replacing specific data in a template string, support `${xxxx}` `{{xxxx}}` and `{xxxx}` * * @example * ```ts * const tmp = "My name is ${name}, I'm ${age} years old." * mapTemplate(tmp, { * name: 'saqqdy', * age: 18 * }) * // My name is saqqdy, I'm 18 years old. * * mapTemplate(tmp, key => ({ name: 'saqqdy', age: 28 }[key])) * // My name is saqqdy, I'm 28 years old. * * const tmp = "My name is {{name}}, I'm {{age}} years old." * mapTemplate(tmp, { * name: 'saqqdy', * age: 18 * }) * // My name is saqqdy, I'm 18 years old. * ``` * @since 5.9.0 * @param tmp - Template string * @param data - Template data of map function * @returns - result */ export declare function mapTemplate(tmp: string, data: ((value: string) => unknown) | Record<string, unknown>): string; export declare type MaybePromiseOrGetter<T> = Promise<T> | (<T>() => Promise<T>); /** * Find the set of differences of multiple arrays that belong to A but not to B/C/D... of the elements of * * @example * ```js * minus([1, 2], [2, '33'], [2, 4]) // [1] * ``` * @since 2.2.1 * @param args - arguments * @returns - new array */ export declare function minus<T = unknown>(...args: T[][]): T[]; export { mountCss } export { mountImg } export { mountJs } export { mountStyle } /** * Return the next zIndex value * * @example * ```js * nextIndex() * // 1 * * nextIndex(1000) * // 1001 * * nextIndex(10, 100) * // 100 * ``` * @since 1.0.2 * @param min - optional, minimum value * @param max - optional, maximum value * @returns - number */ export declare function nextIndex(min?: number, max?: number): number; /** * return the next version, Only version types with no more than 3 digits are supported. (Follow the npm version rules) * * @example * ```js * nextVersion('1.2.33') // 1.2.34 * * nextVersion('1.2.33', 'major') // 2.0.0 * * nextVersion('1.2.33', 'premajor', 'alpha') // 2.0.0-alpha.1 * ``` * @since 5.10.0 * @param version - version(like: 1.0.0) * @param type - optional, version type * @param preid - optional, prerelease id * @returns - new version */ export declare function nextVersion(version: string, type?: 'major' | 'minor' | 'patch' | 'premajor' | 'preminor' | 'prepatch' | 'prerelease', preid?: string): string; export declare type OmitPartial<T, K extends keyof T> = { [P in K]: T[P]; } & Omit<Partial<T>, K>; export declare type OmitRequired<T, K extends keyof T> = { [P in K]: T[P]; } & Omit<Required<T>, K>; /** * Open link in new tab (file jump download if browser can't parse) * * @since 1.0.6 * @param url - link */ export declare function openUrl(url: string): void; export declare interface OsVersion { name: 'Windows' | 'MacOS' | 'Android' | 'iOS' | 'WindowsPhone' | 'Debian' | 'WebOS' | 'Harmony'; version: string; } /** * Get the system name and version * * @example * ``` * // ipad => 'Mozilla/5.0 (iPad; CPU OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/87.0.4280.77 Mobile/15E148 Safari/604.1' * osVersion() // \{ name: 'iOS', version: '13.3' \} * * // iphone => 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1' * osVersion() // \{ name: 'iOS', version: '13.2.3' \} * * // mac os => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' * osVersion() // \{ name: 'MacOS', version: '10.15.7' \} * * // windows => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' * osVersion() // \{ name: 'Windows', version: '10.0' \} * * // windows xp => 'Mozilla/5.0 (Windows NT 5.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' * osVersion() // \{ name: 'Windows', version: 'XP' \} * * // windows phone => 'Mozilla/5.0 (Windows Phone OS 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36' * osVersion() // \{ name: 'WindowsPhone', version: '10.0' \} * * ``` * @since 5.1.0 * @param ua - ua or any ua like string, allowed to be undefined, default is navigator.userAgent * @return OsVersion|null */ export declare function osVersion(ua?: string): OsVersion | null; /** * parse url params * * @example * ```js * parseUrlParam('?key1=100&key2=true&key3=null&key4=undefined&key5=NaN&key6=10.888&key7=Infinity&key8=test') * // \{"key1":"100","key2":"true","key3":"null","key4":"undefined","key5":"NaN","key6":"10.888","key7":"Infinity","key8":"test"\} * * parseUrlParam('?key1=100&key2=true&key3=null&key4=undefined&key5=NaN&key6=10.888&key7=Infinity&key8=test', true) * // \{"key1":100,"key2":true,"key3":null,"key5":NaN,"key6":10.888,"key7":Infinity,"key8":"test"\} * ``` * @since 5.0.0 * @param url - url string (like: ?key1=value1&key2=value2) * @param covert - Converts a specific string to a corresponding value (Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2) * @returns object */ export declare function parseUrlParam(url: string, covert?: boolean): Record<string, unknown>; /** * Collection of common regular expressions * * @deprecated It will be refactored and renamed patterns in the next major release. * @since 1.0.1 * @returns - object */ export declare const pattern: { any: RegExp; number: RegExp; string: RegExp; postcode: RegExp; url: RegExp; username: RegExp; float: RegExp; email: RegExp; mobile: RegExp; chinese: RegExp; tel: RegExp; qq: RegExp; pass: RegExp; json: RegExp; arrjson: RegExp; array: RegExp; isjson: RegExp; textarea: RegExp; mac: RegExp; ip4: RegExp; ip4_pri: RegExp; }; export declare type PickPartial<T, K extends keyof T> = { [P in K]?: T[P]; } & Omit<T, K>; export declare type PickRequired<T, K extends keyof T> = { [P in K]-?: T[P]; } & Omit<T, K>; export declare interface PlainObject { [key: string]: JSONValue; } /** * Image preloading * * @since 5.5.0 * @param images - images url */ export declare function preloader(images: string): HTMLImageElement; export declare function preloader(images: string[]): Record<string, HTMLImageElement>; export declare type Primitive = bigint | boolean | null | number | string | symbol | undefined; /** * Convert an object to a promise like api * * @example * ```js * import { promiseFactory, waiting } from 'js-cool' * * function promise() { * const stats = { * value: 100 * } * * const resolver = () => * new Promise(resolve => * waiting(2000).then(() => { * stats.value = 200 * resolve(stats) * }) * ) * * return promiseFactory(stats, resolver) * } * * const res = promise() // res => 100 * const res = await promise() // res => 200 * ``` * @since 5.10.0 * @param original - original object * @param resolver - resolver function * @returns - result */ export declare function promiseFactory<T extends object>(original: T, resolver: () => Promise<any>): T & PromiseLike<T>; /** * punctual setInterval * * @example * ```js * const printDate = () => console.log(new Date()) * const timer = punctualTimer(printDate, 1000) * console.log(timer.count) // 10 * timer.clear() // clear punctualTimer or use clearTimeout(timer.timer) * ``` * @since 5.18.0 * @param handler - A function to be executed after the timer expires. * @param delay - The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. * @param args - Additional arguments which are passed through to the function specified by handler. */ export declare function punctualTimer<TArgs extends any[]>(handler: (args: void) => void, delay: number, [...args]?: TArgs): PunctualTimerReturns; export declare function punctualTimer<TArgs extends any[]>(handler: (...args: TArgs) => void, delay: number, [...args]?: TArgs): PunctualTimerReturns; export declare interface PunctualTimerReturns { count: number; timer: number | null; clear: () => void; } /** * Generate random hexadecimal colors * * @example * ```js * randomColor() * // #bf444b * * randomColor(200) * // #d6e9d7 * * randomColor(200, 255) * // #d3f9e4 * * randomColor([0, 0, 0], [255, 255, 255]) * // #d6e9d7 * ``` * @since 5.5.0 * @param min - the minimum value of the random numbers, eg: [10, 10, 10] * @param max - the maximum value of the random number, eg: [255, 255, 255] * @returns - result */ export declare function randomColor(min?: number | [number, number, number], max?: number | [number, number, number]): string; /** * Get a random integer * * @example * ```js * randomNumber() * // 8 * * randomNumber(0.1, 0.9) * // 0.8 * ``` * @since 5.0.0 * @param min - the minimum value of the random number * @param max - the maximum value of the random number * @returns - random number */ export declare function randomNumber(min?: number, max?: number): number; /** * Generate n random integers that sum to a fixed sum * * @example * ```js * randomNumbers() * // [8] * * randomNumbers(4, 5) * // [1, 1, 2, 1] * * randomNumbers(4, 5, false) * // [0, 1, 2, 2] * ``` * @since 5.4.0 * @param n - Number of generated integers, default: 1 * @param sum - Sum of generated integers, default: 100 * @param max - Generate integers that are not zero, default: true * @returns - numbers */ export declare function randomNumbers(n?: number, sum?: number, noZero?: boolean): number[]; /** * Get a random string * * @example * ```ts * // 1. No parameters are passed, a 32-bit (possibly) string containing upper and lower case letters and numbers is generated by default * randomString() * // PVSjz902EqYbmxaLtvDnggtnlvt5uFTZ * * // 2. Generate a 16-bit random string * randomString(16) * // coTgZy0mqqMJ1sMM * * // 3. Same effect as #2 above * randomString({ * length: 16 * }) * // ngCI5aPqJm84t90d * * // 4. Generate containing special characters (old way of passing values, not recommended) * randomString(true) * // 0Uby@op3B-sK5]dHl4S|15As.OlHiNXd * * // 5. Same effect as #4 above (recommended) * randomString({ * charTypes: ['uppercase', 'lowercase', 'number', 'special'] * }) * // m,2^vpkrE,F,DbcSFk0=vr&@DJ27j9XK * * // 6. Same effect as #4 above, Limit string length to 16 bits * randomString(16, true) * // dXz[J_sYM^3d8fnA * * // 7. Generate a 16-bit random number * randomString({ * length: 16, * charTypes: 'number' * }) * // 7450026301030286 * * // 8. Elimination of confusing characters: oOLl,9gq,Vv,Uu,I1 * randomString({ * length: 16, * noConfuse: true * }) * // 8DEGna8ppC4mqyew * * // 9. The generated random string must contain at least 1 character of each type of character specified, e.g. to generate a 16-bit password that must contain upper and lower case letters, numbers, and special characters. * randomString({ * length: 16, * strict: true * }) * // PFYAPD5KFqOHIADL * ``` * @since 5.0.0 * @param len - the length of the random string that needs to be obtained * @param options - optional, randomString options * @returns - random string */ export declare function randomString(len?: number, options?: RandomStringOptions | boolean): string; export declare function randomString(len?: RandomStringOptions | boolean, options?: RandomStringOptions | boolean): string; export declare type RandomStringCharType = 'uppercase' | 'lowercase' | 'number' | 'special'; export declare interface RandomStringOptions { length?: number; charTypes?: RandomStringCharType | ArrayOneMore<RandomStringCharType>; /** * Elimination of confusing characters: oOLl,9gq,Vv,Uu,I1 */ noConfuse?: boolean; /** * The generated random string must contain each of the listed character types */ strict?: boolean; } /** * removeEvent removes the event delegate created by addEvent * * @since 1.0.2 * @param element - js dom object * @param type - The type of the event. No need to add on * @param handler - Callback method. */ export declare function removeEvent(element: AnyObject, type: string, handler: AnyFunction): void; /** * Converts RGB component values to color codes. * * @example * ```js * RGBToHex(255, 165, 1) * // 'ffa501' * ``` * @since 1.0.9 * @param r - the 1st value of RGB * @param g - RGB's 2nd value * @param b - RGB's 3rd value * @returns - hex value */ export declare const RGBToHex: (r: number, g: number, b: number) => string; /** * Secure parsing of JSON strings * * @example * ```js * safeParse('100') * // 100 * * safeParse('{"a":"undefined","b":"NaN","c":"Infinity","d":"9007199254740993"}') * // { b: NaN, c: Infinity, d: 9007199254740993n } * ``` * @param data - JSON string * @param covert - Whether to convert data, default: true * @returns - JSON Object */ export declare function safeParse(data: string, covert?: boolean): any; /** * Secure stringify of JSON Object * * @example * ```js * safeStringify(100) * // "10