Read this in other languages: English | 简体中文
Installation
pnpm install js-cool
npm install --save js-cool
Usage
ES6 module
import { osVersion } from 'js-cool'
osVersion()
Node.js require
const { osVersion } = require('js-cool')
osVersion()
Using unpkg CDN
<script src="https://unpkg.com/js-cool@4.4.0/dist/index.global.prod.js"></script>
<script>
jsCool.browserVersion()
</script>
API Reference
Global Parameters
client
the client method returns a browser result object
-
Since: 5.2.0
-
Arguments: none
-
Returns: object
-
Example:
import { client } from 'js-cool'
client.get(['device', 'browser', 'engine', 'os'])
client.get('device')
declare class Client {
matchMap: Record<InfoKeys, boolean>
root: Window & typeof globalThis
navigator: Navigator
constructor(options: ClientOptions)
get(names?: InfoTypes | InfoTypes[]): Partial<{
device: InfoKeys | undefined
os: InfoKeys | undefined
browser: InfoKeys | undefined
engine: InfoKeys | undefined
language: any
network: any
orientation: string | undefined
}>
getInfoByType(infoKey: InfoKey): InfoKeys | undefined
getOrientationStatus(): 'vertical' | 'horizontal' | undefined
getNetwork(): any
getLanguage(): any
}
pattern
pattern returns some common rules
-
Since: 1.0.1
-
Arguments: none
-
Returns: none
-
Example:
pattern.number.test('333')
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
}
clearAttr
Remove all attributes of HTML tags
Parameters | Description | Type | Optional | Required | Default |
---|
string | string with html tags | string | - | true | - |
clearAttr('<div id="testID">test</div>')
declare function clearAttr(string: string): string
clearHtml
Remove HTML tags
Parameters | Description | Type | Optional | Required | Default |
---|
string | string with html tags | string | - | true | - |
clearHtml('<div>test<br />string</div>')
declare function clearHtml(string: string): string
escape
Escaping HTML Special Characters
Parameters | Description | Type | Optional | Required | Default |
---|
string | string with html tags | string | - | true | - |
escape('<div>test<br />string</div>')
declare function escape(string: string): string
unescape
Restore HTML Special Characters
Parameters | Description | Type | Optional | Required | Default |
---|
string | string | string | - | true | - |
unescape('<div>test<br />string</div>')
declare function unescape(string: string): string
getNumber
Get the number in the string
Parameters | Description | Type | Optional | Required | Default |
---|
string | pass in a string with a number | string | - | true | - |
getNumber('Chrome123.33')
getNumber('234test.88')
declare function getNumber(string: string): string
camel2Dash
Converts humped strings to -spaced and all lowercase Dash pattern
Parameters | Description | Type | Optional | Required | Default |
---|
string | the string to be converted | string | - | true | - |
camel2Dash('jsCool')
declare function camel2Dash(string: string): string
dash2Camel
Converts -spaced and all lowercase Dash patterns to humped strings
Parameters | Description | Type | Optional | Required | Default |
---|
string | the string to be converted | string | - | true | - |
dash2Camel('js-cool')
declare function dash2Camel(string: string): string
randomColor
Generate random hexadecimal colors
-
Since: 5.5.0
-
Arguments: none
-
Returns: string
-
Example:
randomColor()
declare function randomColor(): string
randomNumber
Get a random number
Parameters | Description | Type | Optional | Required | Default |
---|
min | the minimum value of the random number | number | - | false | 1 |
max | the maximum value of the random number | number | - | false | 10 |
randomNumber()
randomNumber(0.1, 0.9)
declare function randomNumber(min?: number, max?: number): number
randomNumbers
Generate n random integers that sum to a fixed sum
Parameters | Description | Type | Optional | Required | Default |
---|
n | Number of generated integers | number | - | false | 1 |
sum | Sum of generated integers | number | - | false | 100 |
noZero | Generate integers that are not zero | boolean | - | false | true |
-
Returns: Array<number>
-
Example:
randomNumbers()
randomNumbers(4, 5)
randomNumbers(4, 5, false)
declare function randomNumbers(n?: number, sum?: number): number[]
randomString
Get a random string
v5.4.0 widthSpecialChar
changed to options
, still compatible with old usage, widthSpecialChar=true equivalent to { charTypes: ['uppercase', 'lowercase', 'number', 'special'] }
Parameters | Description | Type | Optional | Required | Default |
---|
len | the length of the random string that needs to be obtained | number | - | false | 32 |
options | randomString options | RandomStringOptions boolean | - | false | { charTypes: ['uppercase', 'lowercase', 'number'] } |
randomString()
randomString(16)
randomString({
length: 16
})
randomString(true)
randomString({
charTypes: ['uppercase', 'lowercase', 'number', 'special']
})
randomString(16, true)
randomString({
length: 16,
charTypes: 'number'
})
randomString({
length: 16,
noConfuse: true
})
randomString({
length: 16,
strict: true
})
declare function randomString(len?: number, options?: RandomStringOptions | boolean): string
declare function randomString(
len?: RandomStringOptions | boolean,
options?: RandomStringOptions | boolean
): string
declare type RandomStringCharType = 'uppercase' | 'lowercase' | 'number' | 'special'
declare interface RandomStringOptions {
length?: number
charTypes?: RandomStringCharType | ArrayOneMore<RandomStringCharType>
noConfuse?: boolean
strict?: boolean
}
shuffle
shuffling algorithm, Reordering arrays or strings
Parameters | Description | Type | Optional | Required | Default |
---|
value | arrays or strings | array string | - | true | - |
size | new array or string length | number | - | false | - |
-
Returns: array | string
-
Example:
const str = 'abcde'
const arr = [1, 2, 3]
shuffle(str)
shuffle(arr)
shuffle(arr, 2)
declare function shuffle(value: string, size?: number): string
declare function shuffle<T extends unknown[] = unknown[]>(value: T, size?: number): T
fingerprint
Generating Browser Fingerprints
Parameters | Description | Type | Optional | Required | Default |
---|
domain | key string | string | - | false | location.host |
fingerprint('www.saqqdy.com')
declare function fingerprint(domain?: string): string | null
getCHSLength
Get the length of the string, Chinese counts as 2 characters
Parameters | Description | Type | Optional | Required | Default |
---|
str | input string | string | - | true | - |
getCHSLength('测试')
declare function getCHSLength(str: string): number
cutCHSString
Intercept string, Chinese counts as 2 bytes
Parameters | Description | Type | Optional | Required | Default |
---|
str | the string to be intercepted | string | - | true | - |
len | length | number | - | false | - |
hasDot | output with dot | boolean | - | false | false |
cutCHSString('测试', 1)
cutCHSString('测试', 1, true)
declare function cutCHSString(str: string, len?: number, hasDot?: boolean): string
Determine
isDigitals
Determine if a string is a number
Parameters | Description | Type | Optional | Required | Default |
---|
str | the string to be tested | string | - | true | - |
-
Returns: boolean
-
Example:
isDigitals('2.11')
isDigitals('2.3x')
declare function isDigitals(str: string): boolean
isExitsFunction
Determine if a function is defined
Parameters | Description | Type | Optional | Required | Default |
---|
name | function name | string | - | true | - |
-
Returns: boolean
-
Example:
isExitsFunction('test')
isExitsFunction('console.log')
declare function isExitsFunction(name: string): boolean
isExitsVariable
Determine if a variable is defined
Parameters | Description | Type | Optional | Required | Default |
---|
name | variable name | string | - | true | - |
-
Returns: boolean
-
Example:
isExitsVariable('test')
isExitsVariable('window')
declare function isExitsVariable(name: string): boolean
isWindow
Determine if window object
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
-
Returns: boolean
-
Example:
isWindow({})
isWindow(window)
declare function isWindow<T = any>(target: T): target is Window
isPlainObject
Determine if target is an plain object
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
-
Returns: boolean
-
Example:
isPlainObject({})
isPlainObject(window)
type Primitive = bigint | boolean | null | number | string | symbol | undefined
type JSONValue = Primitive | PlainObject | JSONArray
interface PlainObject {
[key: string]: JSONValue
}
interface JSONArray extends Array<JSONValue> {}
declare function isPlainObject(target: unknown): target is PlainObject
isDarkMode
Determine if dark color mode
-
Since: 5.5.0
-
Arguments: none
-
Returns: boolean
-
Example:
isDarkMode()
declare function isDarkMode(): boolean
isObject
Determine if target is an object
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
-
Returns: boolean
-
Example:
isObject({})
declare function isObject<T = any>(target: T): target is Object
isArray
Determine if it is an array
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
-
Returns: boolean
-
Example:
isArray([])
declare function isIterable(target: any): target is any[]
isIterable
Determine if it is iterable
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
-
Returns: boolean
-
Example:
isIterable([])
declare function isIterable<T = any>(target: T | Iterable<T>): target is Iterable<T>
inBrowser
Determine if it is running on the browser side
-
Since: 4.5.0
-
Arguments: none
-
Returns: boolean
-
Example:
function test() {
if (!inBrowser) return null
}
declare const inBrowser: boolean
windowSize
Get the window size
windowSize()
declare interface WindowSizeObj {
width: number
height: number
}
declare function windowSize(): WindowSizeObj
getAppVersion
Get the APP version number
deprecated please use 'appVersion' instead
Parameters | Description | Type | Optional | Required | Default |
---|
appName | app name | string | - | true | - |
withApp | whether to bring the name | boolean | - | false | - |
userAgent | ua or any ua like string, may not be passed | string | - | false | navigator.userAgent |
getAppVersion('Chrome')
getAppVersion('Safari', true)
declare function getAppVersion(
appName: string,
withApp?: boolean,
userAgent?: string
): string | boolean | null
appVersion
Get the app version number
Parameters | Description | Type | Optional | Required | Default |
---|
appName | app name | string | - | true | - |
ua | ua or any ua like string, may not be passed | string | - | false | navigator.userAgent |
ignoreCase | whether to ignore case | boolean | true/false | false | true |
-
Returns: string | null
-
Example:
appVersion('Chrome')
appVersion('Safari')
appVersion('appname', false)
appVersion('appname')
declare function appVersion(appName: string): string | null
declare function appVersion(appName: string, ua: string): string | null
declare function appVersion(appName: string, ua: boolean): string | null
declare function appVersion(appName: string, ua: string, ignoreCase: boolean): string | null
getOsVersion
Get the phone system version
deprecated: please use 'osVersion' instead
Parameters | Description | Type | Optional | Required | Default |
---|
osName | system type string Android, iPod, iWatch or iPhone | string | - | true | - |
withOS | whether to bring the name | string | - | false | - |
userAgent | ua or any ua like string, may not be passed | string | - | false | navigator.userAgent |
getOsVersion('iPhone')
getOsVersion('iPhone', true)
declare function getOsVersion(
osName: string,
withOS?: boolean,
userAgent?: string
): string | boolean | null
osVersion
get the system version
Parameters | Description | Type | Optional | Required | Default |
---|
ua | ua or any ua like string, may not be passed | string | - | false | navigator.userAgent |
osVersion()
osVersion()
osVersion()
osVersion()
osVersion()
osVersion()
declare interface OsVersion {
name: 'Windows' | 'MacOS' | 'Android' | 'iOS' | 'WindowsPhone' | 'Debian' | 'WebOS'
version: string
}
declare function osVersion(ua?: string): OsVersion | null
browserVersion
Get the browser name and version
Parameters | Description | Type | Optional | Required | Default |
---|
ua | ua or any ua like string, may not be passed | string | - | false | navigator.userAgent |
browserVersion()
declare interface BrowserVersion {
name: 'Windows' | 'MacOS' | 'Android' | 'iOS' | 'WindowsPhone' | 'Debian' | 'WebOS'
version: string
}
declare function browserVersion(ua?: string): BrowserVersion | null
compareVersion
Version number size comparison
Parameters | Description | Type | Optional | Required | Default |
---|
input | input version | string | - | true | - |
compare | compare version | string | - | true | - |
-
Returns: 0 | 1 | -1
-
Example:
compareVersion('1.11.0', '1.9.9')
compareVersion('1.11.0', '1.11.0')
compareVersion('1.11.0', '1.99.0')
declare function compareVersion(input: string, compare: string): 0 | 1 | -1
parseUrlParam
parse url params. (If covert is passed true: Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2)
Parameters | Description | Type | Optional | Required | Default |
---|
url | url string (like: ?key1=value1&key2=value2) | string | - | true | - |
covert | Converts a specific string to a corresponding value | boolean | true /false | false | false |
parseUrlParam(
'?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
)
declare function parseUrlParam(url: string, covert?: boolean): Record<string, unknown>
spliceUrlParam
Splice URL parameters (single layer only)
Parameters | Description | Type | Optional | Required | Default |
---|
params | json object | object | - | true | - |
covert | Convert a null value type (null/undefined/) to an empty string | boolean | true /false | false | false |
withQuestionsMark | Splicing a question mark | boolean | true /false | false | true |
spliceUrlParam({ key1: '100', key2: 'true', key3: 'null', key4: 'undefined', key4: '测试' })
spliceUrlParam({ key1: '100', key2: 'true', key3: 'null', key4: 'undefined' }, true)
spliceUrlParam({ key1: '100', key2: 'true', key3: 'null', key4: 'undefined' }, true, false)
declare function spliceUrlParam(
params: Record<string, unknown>,
covert?: boolean,
withQuestionsMark?: boolean
): string | null
getDirParam
Get the URL parameter in the form of a directory
It will be refactored and renamed getDirParams in the next major release.
Parameters | Description | Type | Optional | Required | Default |
---|
url | http url | object | - | true | - |
declare interface DirParamType {
path?: string[]
host?: string
}
declare function getDirParam(url: string): DirParamType
getQueryParam
Get a single query parameter (behind "#")
Parameters | Description | Type | Optional | Required | Default |
---|
key | key name | string | - | true | - |
url | pass in the url string | string | - | false | location.href |
getQueryParam('key1')
getQueryParam('key1', 'https://test.com?key1=100#/home?key1=200')
declare function getQueryParam(key: string): string | undefined
declare function getQueryParam(key: string, url: string): string | undefined
getQueryParams
Get all query parameters (behind "#"). (If covert is passed true: Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2)
Parameters | Description | Type | Optional | Required | Default |
---|
url | pass in the url string | string | - | false | location.href |
covert | Converts a specific string to a corresponding value | boolean | true /false | false | false |
getQueryParams('https://test.com?key1=100#/home?key1=200')
getQueryParams('https://test.com?key1=100#/home?key1=200', true)
getQueryParams(true)
declare function getQueryParams(url?: string, covert?: boolean): Record<string, unknown> | null
getUrlParam
Get a single URL parameter (from the "location.search", before "#")
Parameters | Description | Type | Optional | Required | Default |
---|
key | key name | string | - | true | - |
url | pass in the url string | string | - | false | location.href |
getUrlParam('key1')
getUrlParam('key1', 'https://test.com?key1=100#/home?key1=200')
declare function getUrlParam(key: string): string | undefined
declare function getUrlParam(key: string, url: string): string | undefined
getUrlParams
Get all URL parameters (from the "location.search", before "#"). (If covert is passed true: Scientific notation, binary, octal and hexadecimal types of data are not converted, like: 0b111, 0o13, 0xFF, 1e3, -1e-2)
Parameters | Description | Type | Optional | Required | Default |
---|
url | pass in the url string | string | - | false | location.href |
covert | Converts a specific string to a corresponding value | boolean | true /false | false | false |
getUrlParams('https://test.com?key1=100#/home?key1=200')
getUrlParams('https://test.com?key1=100#/home?key1=200', true)
getUrlParams(true)
declare function getUrlParams(url?: string, covert?: boolean): Record<string, unknown> | null
localStorage & sessionStorage & Cookie
getCache
Get the cache, if the deposited is Object, the retrieved is also Object, no need to convert again
Parameters | Description | Type | Optional | Required | Default |
---|
name | cache key name | string | - | true | - |
import { getCache, setCache } from 'js-cool'
const data1 = 100
const data2 = { a: 10 }
const data3 = null
setCache('data1', data1)
setCache('data2', data2)
setCache('data3', data3)
getCache('data1')
getCache('data2')
getCache('data3')
getCache('data4')
declare function getCache(name: string): any
setCache
Set the cache, if the deposited is Object, the retrieved is also Object, no need to convert again
Parameters | Description | Type | Optional | Required | Default |
---|
name | cache key name | string | - | true | - |
value | cache data, can be passed directly into Object | any | - | true | - |
seconds | cache time (seconds) | number | - | false | - |
import { getCache, setCache } from 'js-cool'
const data1 = 100
const data2 = { a: 10 }
const data3 = null
setCache('data1', data1)
setCache('data2', data2, 10)
getCache('data1')
getCache('data2')
setTimeout(() => {
getCache('data2')
}, 15000)
declare function setCache<T = unknown>(name: string, value: T, seconds?: number | string): void
delCache
Delete localStorage
Parameters | Description | Type | Optional | Required | Default |
---|
name | cache key name | string | - | true | - |
delCache('data')
declare function delCache(name: string): void
getSession
Get the session, if the deposited is Object, the retrieved is also Object, no need to convert again
Parameters | Description | Type | Optional | Required | Default |
---|
name | session key name | string | - | true | - |
const data1 = 100
const data2 = { a: 10 }
const data3 = null
setSession('data1', data1)
setSession('data2', data2)
setSession('data3', data3)
getSession('data1')
getSession('data2')
getSession('data3')
getSession('data4')
declare function getSession(name: string): any
setSession
Set the session, if the deposited is Object, the retrieved is also Object, no need to convert again
Parameters | Description | Type | Optional | Required | Default |
---|
name | session key name | string | - | true | - |
value | session data, can be passed directly into Object | any | - | true | - |
seconds | session time (seconds) | number | - | false | - |
import { getSession, setSession } from 'js-cool'
const data1 = 100
const data2 = { a: 10 }
const data3 = null
setSession('data1', data1)
setSession('data2', data2, 10)
getSession('data1')
getSession('data2')
setTimeout(() => {
getSession('data2')
}, 15000)
declare function setSession<T = unknown>(name: string, value: T, seconds?: number | string): void
delSession
Delete sessionStorage
Parameters | Description | Type | Optional | Required | Default |
---|
name | session key name | string | - | true | - |
delSession('data')
declare function delSession(name: string): void
getCookie
Get cookie by name
Parameters | Description | Type | Optional | Required | Default |
---|
name | cookie key name | string | - | true | - |
getCookie('data1')
declare function getCookie(name: string): string
getCookies
Get all cookies
-
Since: 5.6.0
-
Arguments: 'none'
-
Returns: object
-
Example:
getCookies()
declare function getCookies(): Record<string, string>
setCookie
Set cookie
Parameters | Description | Type | Optional | Required | Default |
---|
name | cookie key name | string | - | true | - |
value | cookie data, can be passed directly into Object | any | - | true | - |
seconds | cookie time (seconds) | number | - | false | - |
path | cookie path | string | - | false | / |
samesite | SameSite type | string | Strict /Lax /None | false | None |
import { getCookie, setCookie } from 'js-cool'
const data1 = 100
const data2 = 200
setCookie('data1', data1)
setCookie('data2', data2, 10)
getCookie('data1')
getCookie('data2')
setTimeout(() => {
getCookie('data2')
}, 15000)
declare function setCookie<T extends string | number | boolean>(
name: string,
value: T,
seconds: string | number,
path?: string,
samesite?: boolean
): void
delCookie
Delete cookie
Parameters | Description | Type | Optional | Required | Default |
---|
name | cookie key name | string | - | true | - |
delCookie('data')
declare function delCookie(name: string): void
Base64 & UTF8
encodeBase64
convert strings, numbers to base64
Parameters | Description | Type | Optional | Required | Default |
---|
input | the string to be encoded | string /number | - | true | - |
encodeBase64('data')
declare function encodeBase64(name: string): string
decodeBase64
base64 decoding
Parameters | Description | Type | Optional | Required | Default |
---|
input | the string to be decoded | string /number | - | true | - |
decodeBase64('data')
declare function decodeBase64(name: string): string
encodeUtf8
convert strings, numbers to utf8
Parameters | Description | Type | Optional | Required | Default |
---|
input | the string to be encoded | string /number | - | true | - |
encodeUtf8('data')
declare function encodeUtf8(name: string): string
decodeUtf8
utf8 decoding
Parameters | Description | Type | Optional | Required | Default |
---|
input | the string to be decoded | string /number | - | true | - |
decodeUtf8('data')
declare function decodeUtf8(name: string): string
Events
stopBubble
stop bubbling
Parameters | Description | Type | Optional | Required | Default |
---|
e | dom's event object | Event | - | true | - |
-
Returns: boolean
-
Example:
stopBubble(event)
declare function stopBubble(e: Event): boolean
stopDefault
stop default events
Parameters | Description | Type | Optional | Required | Default |
---|
e | dom's event object | Event | - | true | - |
-
Returns: boolean
-
Example:
stopDefault(event)
declare function stopDefault(e: Event): boolean
addEvent
event delegate, support multiple delegates
Parameters | Description | Type | Optional | Required | Default |
---|
element | js dom object | HTMLElement | - | true | - |
type | The type of the event. No need to add on | string | - | true | - |
handler | Callback method | function | - | true | - |
addEvent(document, 'click', functionName)
declare function addEvent(element: AnyObject, type: string, handler: AnyFunction): void
removeEvent
removeEvent removes the event delegate created by addEvent
Parameters | Description | Type | Optional | Required | Default |
---|
element | js dom object | HTMLElement | - | true | - |
type | The type of the event. No need to add on | string | - | true | - |
handler | Callback method | function | - | true | - |
removeEvent(document, 'click', functionName)
declare function removeEvent(element: AnyObject, type: string, handler: AnyFunction): void
getScrollPosition
Get slide to top and bottom return 'top' 'bottom', recommend using limit flow
getScrollPosition()
declare function getScrollPosition(): string | void
Utilities
nextIndex
return the next zIndex value
change mix defaults to 0
Parameters | Description | Type | Optional | Required | Default |
---|
min | minimum value | number | - | false | 0 |
max | maximum value | number | - | false | - |
nextIndex()
nextIndex(1000)
nextIndex(10, 100)
declare function nextIndex(min?: number, max?: number): number
fixNumber
truncate a few decimal places, not 0 for shortage
Parameters | Description | Type | Optional | Required | Default |
---|
number | the number of digits to be processed | number /string | - | true | - |
n | the number of decimal places to keep | number | - | false | 2 |
-
Returns: string | number
-
Example:
fixNumber('100.888')
fixNumber('100.8', 2)
fixNumber('100.8888', 3)
declare function fixNumber(number: string | number, n?: number): number
extend
deep copy
Parameters | Description | Type | Optional | Required | Default |
---|
target | boolean or array or object | boolean /ArrayOneMore<ExtendData> | - | true | - |
...args | array or object | ArrayOneMore<ExtendData> | - | true | - |
-
Returns: array | object
-
Example:
extend(true, {}, {})
declare function extend(
target: ExtendObjectData,
...args: ArrayOneMore<ExtendObjectData>
): ExtendObjectData
declare function extend(target: boolean, ...args: ArrayOneMore<ExtendObjectData>): ExtendObjectData
declare function extend(
target: ExtendArrayData,
...args: ArrayOneMore<ExtendArrayData>
): ExtendArrayData
declare function extend(target: boolean, ...args: ArrayOneMore<ExtendArrayData>): ExtendArrayData
declare type ExtendArrayData = any[]
declare type ExtendData = ExtendArrayData | ExtendObjectData
declare type ExtendObjectData = Record<string, any>
delay
anti-dither throttling
-
Since: 1.0.2
-
Arguments: none
-
Returns: void
-
Example:
const delay = new Delay()
delay.register('key', () => {
})
declare function delay(): {
map: any
register(id: string, fn: AnyFunction, time: number, boo: boolean): void
destroy(id: string): void
}
getType
Get the target type
Parameters | Description | Type | Optional | Required | Default |
---|
target | any target | any | - | true | - |
getType({})
getType([])
getType(new Promise())
getType(new Date())
getType(async () => {})
getType(navigator)
getType(global)
getType(window)
getType(Symbol(''))
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'
cleanData
Data cleaning methods
Parameters | Description | Type | Optional | Required | Default |
---|
data | the object to be cleaned | object | - | true | - |
map | the data queue to be cleaned, can be passed as array or object | array /object | - | true | - |
nullFix | the value returned if there is no corresponding property, the default does not return the property | any | - | false | - |
declare function cleanData(data: any, map: any[] | AnyObject, nullFix?: any): any
download
Several ways of file downloading:
- For file formats that some browsers do not recognize. Enter the file URL in the address bar, window.location.href = URL, window.open(URL);
- using a tag download attribute (or js create a tag);
- browser-recognizable pdf, txt files, back-end compatible with handling attachment;
- add token in the header for authenticated download, use XmlHttpRequest to want to backend to launch the request
Parameters | Description | Type | Optional | Required | Default |
---|
url | url link | string | - | true | - |
filename | file name | string | - | true | - |
type | download type | string | href /open /download /request | false | download |
download('https://unpkg.com/browse/js-cool@5.2.0/dist/index.global.prod.js')
declare function download(url: string, filename: string, type?: string): void
searchObject
tree object depth lookup
Parameters | Description | Type | Optional | Required | Default |
---|
tree | tree object | array /object | - | true | - |
expression | required Query method | any | - | true | - |
keySet | optional Default subclass name, query name | SearchKeySet | - | true | - |
number | optional Number of lookups, if not passed, query all | number | - | false | - |
declare function searchObject(
tree: object | any[],
expression: any,
keySet: SearchKeySet,
number?: number
): any[]
openUrl
Open link in new tab (file jump download if browser can't parse)
Parameters | Description | Type | Optional | Required | Default |
---|
url | http url | string | - | true | - |
openUrl('https://www.saqqdy.com/js-cool')
declare function openUrl(url: string): void
copy
copy to clipboard
Parameters | Description | Type | Optional | Required | Default |
---|
value | any value | any | - | true | - |
copy('10000')
declare function copy(value: string): boolean | undefined
toThousands
Digital thousandths division
Parameters | Description | Type | Optional | Required | Default |
---|
num | the number | string /number | - | true | - |
toThousands(10000)
declare function toThousands(num: string | number): string
all
return true if the provided predicate function returns true for all elements in a set, otherwise return false
Parameters | Description | Type | Optional | Required | Default |
---|
arr | the target array | array | - | true | - |
fn | the judgment method | function | - | true | - |
-
Returns: boolean
-
Example:
all([4, 2, 3], x => x > 1)
declare const all: <T = unknown>(arr: T[], fn: AnyFunction) => boolean
any
Returns true if the provided predicate function returns true for at least one element of a set, false otherwise
Parameters | Description | Type | Optional | Required | Default |
---|
arr | the target array | array | - | true | - |
fn | the judgment method | function | - | true | - |
-
Returns: boolean
-
Example:
any([0, 1, 2, 0], x => x >= 2)
declare const any: <T = unknown>(arr: T[], fn: AnyFunction) => boolean
uuid
generate uuid on browser side, use v4 method
-
Since: 1.0.9
-
Arguments: none
-
Returns: string
-
Example:
uuid()
declare const uuid: () => string
CSVToArray
Converts a comma-separated string of values (CSV) to a 2D array.
Parameters | Description | Type | Optional | Required | Default |
---|
data | csv data | string | - | true | - |
delimiter | delimiter | string | - | false | ',' |
omitFirstRow | the first row is the table header data | boolean | - | false | false |
CSVToArray('a,b\\nc,d')
CSVToArray('a;b\\\nc;d', ';')
CSVToArray('col1,col2\\\na,b\\\nc,d', ',', true)
declare const CSVToArray: (data: string, delimiter?: string, omitFirstRow?: boolean) => string[][]
arrayToCSV
Converts a two-dimensional array to a comma-separated string of values (CSV).
Parameters | Description | Type | Optional | Required | Default |
---|
arr | json data | array | - | true | - |
delimiter | delimiter | string | - | false | ',' |
arrayToCSV([
['a', 'b'],
['c', 'd']
])
arrayToCSV(
[
['a', 'b'],
['c', 'd']
],
';'
)
arrayToCSV([
['a', '"b" great'],
['c', 3.1415]
])
declare function arrayToCSV<T extends unknown[][]>(data: T, delimiter?: string): string
CSVToJSON
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.
Parameters | Description | Type | Optional | Required | Default |
---|
data | csv data | string | - | true | - |
delimiter | delimiter | string | - | false | ',' |
CSVToJSON('col1,col2\\na,b\\\nc,d')
CSVToJSON('col1;col2\\\na;b\\\nc;d', ';')
declare function CSVToJSON(data: string, delimiter?: string): any[]
JSONToCSV
Converts an array of objects to a comma-separated value (CSV) string containing only the specified columns.
Parameters | Description | Type | Optional | Required | Default |
---|
arr | json data | array | - | true | - |
columns | the specified columns | array | - | true | - |
delimiter | delimiter | string | - | false | ',' |
JSONToCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'])
JSONToCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';')
declare const JSONToCSV: (arr: any[], columns: any[], delimiter?: string) => string
RGBToHex
Converts RGB component values to color codes.
Parameters | Description | Type | Optional | Required | Default |
---|
r | the 1st value of RGB | number | - | true | - |
g | RGB's 2nd value | number | - | true | - |
b | RGB's 3nd value | number | - | true | - |
RGBToHex(255, 165, 1)
declare const RGBToHex: (r: number, g: number, b: number) => string
intersect
Find the intersection of multiple arrays
Parameters | Description | Type | Optional | Required | Default |
---|
...arr | array targets | array | - | true | - |
intersect([1, 2], [2, 3, 4], [2, 8], [2, '33'])
declare function intersect<T = unknown>(...args: T[][]): T[]
union
Find the concatenation of multiple arrays
Parameters | Description | Type | Optional | Required | Default |
---|
...arr | array targets | array | - | true | - |
union([1, 2], [2, '33'])
declare function union<T = unknown>(...args: T[][]): T[]
minus
Find the set of differences of multiple arrays that belong to A but not to B/C/D... of the elements of
Parameters | Description | Type | Optional | Required | Default |
---|
...arr | array targets | array | - | true | - |
minus([1, 2], [2, '33'], [2, 4])
declare function minus<T = unknown>(...args: T[][]): T[]
complement
Find the complement of multiple arrays
Parameters | Description | Type | Optional | Required | Default |
---|
...arr | array targets | array | - | true | - |
complement([1, 2], [2, '33'], [2])
declare function complement<T = unknown>(...args: T[][]): T[]
contains
Whether the array contains the specified element
Parameters | Description | Type | Optional | Required | Default |
---|
arr | array target | array | - | true | - |
item | any array member | any | - | true | - |
-
Returns: boolean
-
Example:
contains([1, 2], 2)
contains([1, 2], 3)
declare function contains(arr: any[], item: any): boolean
unique
Array de-duplication
Parameters | Description | Type | Optional | Required | Default |
---|
arr | array target | array | - | true | - |
unique([1, 2, 2, '33'])
declare function unique<T = unknown>(arr: T[]): T[]
fillIPv6
ipv6 address completion
Parameters | Description | Type | Optional | Required | Default |
---|
ip | ip address | string | - | true | - |
fillIPv6('2409:8005:800::2')
fillIPv6('2409:8005:800::1c')
declare function fillIPv6(ip: string): string
getProperty
Get array, object property values based on path string
Parameters | Description | Type | Optional | Required | Default |
---|
target | target array, object | array /object | - | true | - |
prop | query target, can pass function | string /function | - | true | - |
const target = {
a: 1,
b: [
{
c: 2
}
]
}
getProperty(target, 'a')
getProperty(target, 'b[0].c')
getProperty(target, () => 'a')
declare function getProperty(
target: any,
prop:
| string
| {
(): string
}
): any
setProperty
Set array, object property values based on path string
Parameters | Description | Type | Optional | Required | Default |
---|
target | target array, object | array /object | - | true | - |
prop | set target, can pass function, 'a' | 'a[1].c' | string /function | - | true | - |
value | value | any | - | true | - |
const target = {
a: 1,
b: [
{
c: 2
}
]
}
setProperty(target, 'a')
setProperty(target, 'b[0].c')
setProperty(target, () => 'a')
declare function setProperty(
target: any,
prop:
| string
| {
(): string
},
value: any
): any
loadSource
load resources dynamically, support js, images, css links, css style strings
Parameters | Description | Type | Optional | Required | Default |
---|
url | link to the resource, type must be passed when passing in styleString | string | - | true | - |
options | parameters: attrs, props, force | SourceOptions | - | false | - |
loadSource('/source/url', options)
import { ImageAttributes } from 'mount-image'
import { LinkAttributes } from 'mount-css'
import { ScriptAttributes } from 'mount-script'
import { StyleAttributes } from 'mount-style'
declare function loadSource(
url: string,
option: SourceFileType | SourceOptions
): Promise<boolean | string>
declare type SourceFileType = 'js' | 'img' | 'css' | 'style' | string
declare interface SourceOptions {
type: SourceFileType
attrs?: LinkAttributes | StyleAttributes | ScriptAttributes | ImageAttributes
props?: LinkAttributes | StyleAttributes | ScriptAttributes | ImageAttributes
force?: boolean
}
mountCss
dynamically load css link resources
Parameters | Description | Type | Optional | Required | Default |
---|
url | resource url | string | - | true | - |
options | parameters: attrs, props, force | CssOptions | - | false | - |
-
Returns: boolean
-
Example:
mountCss('/source/url', options)
declare interface CssOptions {
attrs?: LinkAttributes
props?: LinkAttributes
force?: boolean
}
declare interface HTMLLinkElementEX extends HTMLLinkElement {
onreadystatechange?: any
readyState?: 'loaded' | 'complete'
}
declare type LinkAttributes = Pick<
HTMLLinkElement,
| 'as'
| 'charset'
| 'crossOrigin'
| 'disabled'
| 'href'
| 'hreflang'
| 'imageSizes'
| 'imageSrcset'
| 'integrity'
| 'media'
| 'referrerPolicy'
| 'rel'
| 'rev'
| 'target'
| 'type'
>
declare function mountCss(src: string, option?: CssOptions): Promise<boolean>
mountImg
load image resource dynamically
Parameters | Description | Type | Optional | Required | Default |
---|
url | resource url | string | - | true | - |
options | parameters: attrs, props, force | ImgOptions | - | false | - |
mountImg('/source/url', options)
declare interface HTMLImageElementEX extends HTMLImageElement {
onreadystatechange?: any
readyState?: 'loaded' | 'complete'
}
declare type ImageAttributes = Pick<
HTMLImageElement,
| 'align'
| 'alt'
| 'border'
| 'crossOrigin'
| 'decoding'
| 'height'
| 'hspace'
| 'isMap'
| 'loading'
| 'longDesc'
| 'lowsrc'
| 'name'
| 'referrerPolicy'
| 'sizes'
| 'src'
| 'srcset'
| 'useMap'
| 'vspace'
| 'width'
>
declare interface ImgOptions {
attrs?: ImageAttributes
props?: ImageAttributes
force?: boolean
}
declare function mountImage(src: string, option?: ImgOptions): Promise<boolean | string>
mountJs
load js link resources dynamically
Parameters | Description | Type | Optional | Required | Default |
---|
url | resource url | string | - | true | - |
options | parameters: attrs, props, force | JsOptions | - | false | - |
-
Returns: boolean
-
Example:
mountJs('/source/url', options)
declare interface HTMLScriptElementEX extends HTMLScriptElement {
onreadystatechange?: any
readyState?: 'loaded' | 'complete'
}
declare interface JsOptions {
attrs?: ScriptAttributes
props?: ScriptAttributes
force?: boolean
}
declare function mountJs(src: string, option?: JsOptions): Promise<boolean>
declare type ScriptAttributes = Pick<
HTMLScriptElement,
| 'async'
| 'charset'
| 'crossOrigin'
| 'defer'
| 'event'
| 'htmlFor'
| 'integrity'
| 'noModule'
| 'referrerPolicy'
| 'src'
| 'text'
| 'type'
>
mountStyle
load css styles dynamically
Parameters | Description | Type | Optional | Required | Default |
---|
url | resource url | string | - | true | - |
options | parameters: attrs, props, force | StyleOptions | - | false | - |
-
Returns: boolean
-
Example:
mountStyle('/source/url', options)
declare function mountStyle(css: string, option?: StyleOptions): Promise<boolean>
declare type StyleAttributes = Pick<HTMLStyleElement, 'disabled' | 'media' | 'type'>
declare interface StyleOptions {
attrs?: StyleAttributes
props?: StyleAttributes
}
preloader
Image preloading
Parameters | Description | Type | Optional | Required | Default |
---|
images | images url | string array | - | true | - |
preloader('path/of/image')
preloader(['path/of/image'])
declare function preloader(images: string): HTMLImageElement
declare function preloader(images: string[]): Record<string, HTMLImageElement>
waiting
waiting for a while
Parameters | Description | Type | Optional | Required | Default |
---|
milliseconds | waiting time (milliseconds) | number | - | true | - |
-
Returns: Promise<void>
-
Example:
waiting(2000)
declare function waiting(milliseconds: number): Promise<void>
awaitTo
Async await wrapper for easy error handling
v5.7.0 Extend awaitTo to support passing in multiple promises
Parameters | Description | Type | Optional | Required | Default |
---|
promise | promise function | Promise Promise[] | - | true | - |
...promises | Promise rest params | Promise[] | - | false | - |
import { awaitTo as to } from 'js-cool'
const [err, data] = await to(new Promise())
if (err) {
}
const [err, data] = await to(promise1, promise2)
const [err, data] = await to([promise1, promise2])
declare function awaitTo<T, E = Error>(promise: Promise<T>): Promise<[E, undefined] | [null, T]>
Support & Issues
Please open an issue here.
License
MIT