Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

js-cool

Package Overview
Dependencies
Maintainers
1
Versions
94
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-cool

Collection of common JavaScript / TypeScript utilities

  • 5.21.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
200
increased by212.5%
Maintainers
1
Weekly downloads
 
Created
Source

js-cool

Collection of common JavaScript / TypeScript utilities

NPM version Codacy Badge tree shaking typescript Test coverage npm download gzip License

Sonar

DocumentationChange Log

Read this in other languages: English | 简体中文

  • Installation
  • Usage
  • API Reference
    • Global Parameters
      • client - The client method returns a browser result object
      • pattern - Collection of common regular expressions
    • Extras for String & Array & Object & Function
      • clearAttr - Remove all attributes of HTML tags
      • clearHtml - Removing HTML tags
      • escape - Escaping HTML Special Characters
      • unescape - Restore HTML Special Characters
      • getNumber - Get the number in the string
      • camel2Dash - Converts humped strings to -spaced and all lowercase Dash pattern
      • dash2Camel - Converts -spaced and all lowercase Dash patterns to humped strings
      • randomColor - Generate random hexadecimal colors
      • randomNumber - Get a random number
      • randomNumbers - Generate n random integers that sum to a fixed sum
      • randomString - Get a random string
      • shuffle - shuffling algorithm, Reordering arrays or strings
      • fingerprint - Generating Browser Fingerprints
      • getCHSLength - Get the length of the string, Chinese counts as 2 characters
      • cutCHSString - Intercept string, Chinese counts as 2 bytes
      • upperFirst - First letter capitalized
    • Determine
      • isDigitals - Determine if a string is a number
      • isExitsFunction - Determine if a function is defined
      • isExitsVariable - Determine if a variable is defined
      • isEqual - Determine if 2 objects are equal
      • isWindow - Determine if window object
      • isPlainObject - Determine if target is an plain object
      • isDarkMode - Determine if dark color mode
      • isObject - Determine if target is an object
      • isDate - Determine if target is Date
      • isRegExp - Determine if target is RegExp
      • isArray - Determine if it is an array
      • isIterable - Determine if it is iterable
      • inBrowser - Determine if it is running on the browser side
      • inNodeJs - Determine if it is running on node.js
      • windowSize - Get the window size
      • getAppVersion - Get the APP version number
      • appVersion - Get the app version number
      • getOsVersion - Get the phone system version
      • osVersion - get the system version
      • browserVersion - Get the browser name and version
      • compareVersion - Version number size comparison, tag version: rc > beta > alpha > other
      • 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)
      • spliceUrlParam - Splice URL parameters (single layer only)
      • safeParse - Secure parsing of JSON strings
      • safeStringify - Secure stringify of JSON Object
      • getDirParam - Get the URL parameter in the form of a directory
      • getQueryParam - Get a single query parameter (behind "#")
      • 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)
      • getUrlParam - Get a single URL parameter (from the "location.search", before "#")
      • 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)
    • localStorage & sessionStorage & Cookie
      • getCache - Get the cache, if the deposited is Object, the retrieved is also Object, no need to convert again
      • setCache - Set the cache, if the deposited is Object, the retrieved is also Object, no need to convert again
      • delCache - Delete localStorage
      • getSession - Get the session, if the deposited is Object, the retrieved is also Object, no need to convert again
      • setSession - Set the session, if the deposited is Object, the retrieved is also Object, no need to convert again
      • delSession - Delete sessionStorage
      • getCookie - Get cookie by name
      • getCookies - Get all cookies
      • setCookie - Set cookie
      • delCookie - Delete cookie
    • Base64 & UTF8
    • Events
    • Utilities
      • nextIndex - return the next zIndex value
      • nextVersion - return the next version, Only version types with no more than 3 digits are supported. (Follow the npm version rules)
      • punctualTimer - punctual setInterval
      • promiseFactory - Convert an object to a promise like api
      • fixNumber - truncate a few decimal places, not 0 for shortage
      • mapTemplate - Replacing specific data in a template string, support ${xxxx} {{xxxx}} and {xxxx}
      • extend - deep copy & merge objects
      • clone - deep copy (Buffer, Promise, Set, Map are not supported)
      • delay - anti-dither throttling
      • getType - Get the target type
      • getFileType - Determine file type based on link suffix
      • sorter - Sorter factory function
      • sortPinyin - Sort Chinese by Chinese phonetic alphabet
      • cleanData - Data cleaning methods
      • download - Several ways of file downloading
      • searchObject - tree object depth lookup
      • openUrl - Open link in new tab (file jump download if browser can't parse)
      • copy - copy to clipboard
      • toThousands - Digital thousandths division
      • all - return true if the provided predicate function returns true for all elements in a set, otherwise return false
      • any - Returns true if the provided predicate function returns true for at least one element of a set, false otherwise
      • uuid - generate uuid on browser side, use v4 method
      • CSVToArray - Converts a comma-separated string of values (CSV) to a 2D array.
      • arrayToCSV - Converts a two-dimensional array to a comma-separated string of values (CSV).
      • 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.
      • JSONToCSV - Converts an array of objects to a comma-separated value (CSV) string containing only the specified columns.
      • RGBToHex - Converts RGB component values to color codes.
      • intersect - Find the intersection of multiple arrays
      • union - Find the concatenation of multiple arrays
      • minus - Find the set of differences of multiple arrays that belong to A but not to B/C/D... of the elements of
      • complement - Find the complement of multiple arrays
      • contains - Whether the array contains the specified element
      • unique - Array de-duplication
      • fillIPv6 - ipv6 address completion
      • getProperty - Get array, object property values based on path string
      • setProperty - Set array, object property values based on path string
      • loadSource - load resources dynamically, support js, images, css links, css style strings
      • mountCss - dynamically load css link resources
      • mountImg - load image resource dynamically
      • mountJs - load js link resources dynamically
      • mountStyle - load css styles dynamically
      • preloader - Image preloading
      • waiting - waiting for a while
      • awaitTo - Async await wrapper for easy error handling
    • Blob arrayBuffer base64 file blobUrl
  • Support & Issues
  • License

Installation

# use pnpm
pnpm install js-cool

## use npm
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@latest/dist/index.global.prod.js"></script>
<script>
  jsCool.browserVersion()
</script>

API Reference

Global Parameters

client

The client method returns a browser result object

  • Since: 1.0.1

  • Arguments: none

  • Returns: object

  • Example:

import { client } from 'js-cool'

client.get(['device', 'browser', 'engine', 'os']) // { device: 'xxx', browser: 'xxx', os: 'xxx', engine: 'xxx' }
client.get('device') // { device: 'xxx' }
  • Types:
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

Collection of common regular expressions

v5.21.2 pattern support mac/ip4/ip4_pri

  • Since: 1.0.1

  • Arguments: none

  • Returns: none

  • Example:

pattern.number.test('333') // true
  • Types:
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
}

Extras for String & Array & Object & Function

clearAttr

Remove all attributes of HTML tags

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringstring with html tagsstring-true-
  • Returns: string

  • Example:

clearAttr('<div id="testID">test</div>')
// '<div>test</div>'
  • Types:
declare function clearAttr(string: string): string
clearHtml

Remove HTML tags

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringstring with html tagsstring-true-
  • Returns: string

  • Example:

clearHtml('<div>test<br />string</div>')
// 'teststring'
  • Types:
declare function clearHtml(string: string): string
escape

Escaping HTML Special Characters

  • Since: 5.5.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringstring with html tagsstring-true-
  • Returns: string

  • Example:

escape('<div>test<br />string</div>')
// '&lt;div&gt;test&lt;br /&gt;string&lt;/div&gt;'
  • Types:
declare function escape(string: string): string
unescape

Restore HTML Special Characters

  • Since: 5.5.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringstringstring-true-
  • Returns: string

  • Example:

unescape('&lt;div&gt;test&lt;br /&gt;string&lt;/div&gt;')
// '<div>test<br />string</div>'
  • Types:
declare function unescape(string: string): string
getNumber

Get the number in the string

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringpass in a string with a numberstring-true-
  • Returns: string

  • Example:

getNumber('Chrome123.33')
// '123.33'

getNumber('234test.88')
// '234.88'
  • Types:
declare function getNumber(string: string): string
camel2Dash

Converts humped strings to -spaced and all lowercase Dash pattern

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringthe string to be convertedstring-true-
  • Returns: string

  • Example:

camel2Dash('jsCool') // js-cool
  • Types:
declare function camel2Dash(string: string): string
dash2Camel

Converts -spaced and all lowercase Dash patterns to humped strings

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringthe string to be convertedstring-true-
  • Returns: string

  • Example:

dash2Camel('js-cool') // jsCool
  • Types:
declare function dash2Camel(string: string): string
randomColor

Generate random hexadecimal colors

Support for custom color value ranges starting with version 5.17.0, which can be used to customize the generation of darker, lighter, warmer colors, etc.

  • Since: 5.5.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
minthe minimum value of the random numbersnumber / [number, number, number]-false-
maxthe maximum value of the random numbersnumber / [number, number, number]-false-
  • Returns: string

  • Example:

randomColor()
// #bf444b

randomColor(200)
// #d6e9d7

randomColor(200, 255)
// #d3f9e4

randomColor([0, 0, 0], [255, 255, 255])
// #e2f2f3
  • Types:
declare function randomColor(
  min?: number | [number, number, number],
  max?: number | [number, number, number]
): string
randomNumber

Get a random number

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
minthe minimum value of the random numbernumber-false1
maxthe maximum value of the random numbernumber-false10
  • Returns: number

  • Example:

randomNumber() // 8
randomNumber(0.1, 0.9) // 0.8
  • Types:
declare function randomNumber(min?: number, max?: number): number
randomNumbers

Generate n random integers that sum to a fixed sum

  • Since: 5.4.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
nNumber of generated integersnumber-false1
sumSum of generated integersnumber-false100
noZeroGenerate integers that are not zeroboolean-falsetrue
  • Returns: Array<number>

  • Example:

randomNumbers()
// [8]

randomNumbers(4, 5)
// [1, 1, 2, 1]

randomNumbers(4, 5, false)
// [0, 1, 2, 2]
  • Types:
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'] }

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
lenthe length of the random string that needs to be obtainednumber-false32
optionsrandomString optionsRandomStringOptions boolean-false{ charTypes: ['uppercase', 'lowercase', 'number'] }
  • Returns: string

  • Example:

// 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
  • Types:
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>
  /**
   * 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
}
shuffle

shuffling algorithm, Reordering arrays or strings

  • Since: 5.4.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
valuearrays or stringsarray string-true-
sizenew array or string lengthnumber-false-
  • Returns: array | string

  • Example:

const str = 'abcde'
const arr = [1, 2, 3]

shuffle(str)
// cdbse

shuffle(arr)
// [3, 1, 2]

shuffle(arr, 2)
// [3, 2]
  • Types:
declare function shuffle(value: string, size?: number): string

declare function shuffle<T extends unknown[] = unknown[]>(value: T, size?: number): T
fingerprint

Generating Browser Fingerprints

  • Since: 5.2.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
domainkey stringstring-falselocation.host
  • Returns: string

  • Example:

fingerprint('www.saqqdy.com') // wc7sWJJA8
  • Types:
declare function fingerprint(domain?: string): string | null
getCHSLength

Get the length of the string, Chinese counts as 2 characters

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
strinput stringstring-true-
  • Returns: number

  • Example:

getCHSLength('测试') // 2
  • Types:
declare function getCHSLength(str: string): number
cutCHSString

Intercept string, Chinese counts as 2 bytes

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
strthe string to be interceptedstring-true-
lenlengthnumber-false-
hasDotoutput with dotboolean-falsefalse
  • Returns: string

  • Example:

cutCHSString('测试', 1) // 测
cutCHSString('测试', 1, true) // 测...
  • Types:
declare function cutCHSString(str: string, len?: number, hasDot?: boolean): string
upperFirst

First letter capitalized

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
stringthe string to be convertedstring-true-
  • Returns: string

  • Example:

upperFirst('saqqdy') // Saqqdy
  • Types:
declare function upperFirst(string: string): string

Determine

isDigitals

Determine if a string is a number

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
strthe string to be testedstring-true-
  • Returns: boolean

  • Example:

isDigitals('2.11') // true
isDigitals('2.3x') // false
  • Types:
declare function isDigitals(str: string): boolean
isExitsFunction

Determine if a function is defined

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namefunction namestring-true-
  • Returns: boolean

  • Example:

isExitsFunction('test') // false
isExitsFunction('console.log') // true
  • Types:
declare function isExitsFunction(name: string): boolean
isExitsVariable

Determine if a variable is defined

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namevariable namestring-true-
  • Returns: boolean

  • Example:

isExitsVariable('test') // false
isExitsVariable('window') // true
  • Types:
declare function isExitsVariable(name: string): boolean
isEqual

Determine if 2 objects are equal

  • Since: 5.12.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
asourceany-true-
bcompareany-true-
  • Returns: boolean

  • Example:

isEqual({ a: 22, b: {} }, { b: {}, a: 22 })
// true

isEqual([1, 2], [2, 1])
// false

isEqual(NaN, NaN)
// true
  • Types:
declare function isEqual<T, P>(a: T, b: P): boolean
isWindow

Determine if window object

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isWindow({}) // false
isWindow(window) // true
  • Types:
declare function isWindow<T = any>(target: T): target is Window
isPlainObject

Determine if target is an plain object

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isPlainObject({}) // true
isPlainObject(window) // false
  • Types:
type Primitive = bigint | boolean | null | number | string | symbol | undefined

type JSONValue = Primitive | PlainObject | JSONArray

// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
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() // false
  • Types:
declare function isDarkMode(): boolean
isObject

Determine if target is an object

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isObject({}) // true
  • Types:
declare function isObject<T = any>(target: T): target is Object
isDate

Determine if target is Date

  • Since: 5.15.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

const now = new Date()

isDate(now)
// true
  • Types:
declare function isDate<T = any>(target: T): target is Date
isRegExp

Determine if target is RegExp

  • Since: 5.15.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isRegExp(/\d/) // true
  • Types:
declare function isRegExp<T = any>(target: T): target is RegExp
isArray

Determine if it is an array

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isArray([]) // true
  • Types:
declare function isIterable(target: any): target is any[]
isIterable

Determine if it is iterable

  • Since: 5.7.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: boolean

  • Example:

isIterable([]) // true
  • Types:
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
  // ...
}
  • Types:
declare const inBrowser: boolean
inNodeJs

Determine if it is running on node.js

  • Since: 5.13.0

  • Arguments: none

  • Returns: boolean

  • Example:

if (inNodeJs) {
  //
}
  • Types:
declare const inNodeJs: boolean
windowSize

Get the window size

  • Since: 1.0.1

  • Arguments: none

  • Returns: { width, height }

  • Example:

windowSize()
// { width: 1280, height: 800 }
  • Types:
declare interface WindowSizeObj {
  width: number
  height: number
}

declare function windowSize(): WindowSizeObj
getAppVersion

Get the APP version number

deprecated please use 'appVersion' instead

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
appNameapp namestring-true-
withAppwhether to bring the nameboolean-false-
userAgentua or any ua like string, may not be passedstring-falsenavigator.userAgent
  • Returns: string | boolean | null

  • Example:

// 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'

getAppVersion('Chrome') // 114.0.0.0
getAppVersion('Safari', true) // Safari/537.36
  • Types:
declare function getAppVersion(
  appName: string,
  withApp?: boolean,
  userAgent?: string
): string | boolean | null
appVersion

Get the app version number

  • Since: 5.1.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
appNameapp namestring-true-
uaua or any ua like string, may not be passedstring-falsenavigator.userAgent
ignoreCasewhether to ignore casebooleantrue/falsefalsetrue
  • Returns: string | null

  • Example:

// 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
  • Types:
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

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
osNamesystem type string Android, iPod, iWatch or iPhonestring-true-
withOSwhether to bring the namestring-false-
userAgentua or any ua like string, may not be passedstring-falsenavigator.userAgent
  • Returns: string | boolean | null

  • Example:

getOsVersion('iPhone')
// '13.2.3'

getOsVersion('iPhone', true)
// 'iPhone/13.2.3'
  • Types:
declare function getOsVersion(
  osName: string,
  withOS?: boolean,
  userAgent?: string
): string | boolean | null
osVersion

get the system version

  • Since: 5.1.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
uaua or any ua like string, may not be passedstring-falsenavigator.userAgent
  • Returns: OsVersion | null

  • 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' \}
  • Types:
declare interface OsVersion {
  name: 'Windows' | 'MacOS' | 'Android' | 'iOS' | 'WindowsPhone' | 'Debian' | 'WebOS' | 'Harmony'
  version: string
}

declare function osVersion(ua?: string): OsVersion | null
browserVersion

Get the browser name and version

  • Since: 5.2.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
uaua or any ua like string, may not be passedstring-falsenavigator.userAgent
  • Returns: BrowserVersion | null

  • 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' \}
  • Types:
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
}

declare function browserVersion(ua?: string): BrowserVersion | null
compareVersion

v5.8.0 support compare tag version

Version number size comparison, tag version: rc > beta > alpha > other

  • Since: 4.7.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputinput versionstring-true-
comparecompare versionstring-true-
  • Returns: 0 | 1 | -1

  • Example:

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
  • Types:
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)

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlurl string (like: ?key1=value1&key2=value2)string-true-
covertConverts a specific string to a corresponding valuebooleantrue/falsefalsefalse
  • Returns: object

  • Example:

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"\}
  • Types:
declare function parseUrlParam(url: string, covert?: boolean): Record<string, unknown>
spliceUrlParam

Splice URL parameters (single layer only)

v5.20.0 Breaking change: remove encodeURIComponent
v5.21.0 Breaking change: covert support boolean & SpliceUrlParamOptions

  • Since: 5.3.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
paramsjson objectobject-true-
covertConvert a null value type (null/undefined/) to an empty string or spliceUrlParamOptionsboolean | SpliceUrlParamOptions-falsefalse
  • Returns: string

  • Example:

spliceUrlParam({ key1: '100', key2: true, key3: null, key4: undefined, key5: '测试' })
// ?key1=100&key2=true&key3=null&key4=undefined&key5=测试

spliceUrlParam({ key1: '100', key2: true, key3: null, key4: undefined }, true)
// ?key1=100&key2=true&key3=&key4=

spliceUrlParam(
  { key1: '100', key2: true, key3: null, key4: undefined },
  { covert: true, withQuestionsMark: false }
)
// key1=100&key2=true&key3=&key4=
  • Types:
declare function spliceUrlParam<T extends Record<string, unknown>>(
  params: T,
  covert?: SpliceUrlParamOptions | boolean
): string

declare interface SpliceUrlParamOptions {
  covert?: boolean
  encode?: boolean
  withQuestionsMark?: boolean
}
safeParse

Secure parsing of JSON strings

support BigInt since v5.17.1

  • Since: 5.16.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
dataJSON stringstring-true-
covertWhether to convert databooleantrue/falsefalsetrue
  • Returns: Object

  • Example:

safeParse('100')
// 100

safeParse('{"a":"undefined","b":"NaN","c":"Infinity","d":"9007199254740993"}')
// { b: NaN, c: Infinity, d: 9007199254740993n }
  • Types:
declare function safeParse(data: string, covert?: boolean): any
safeStringify

Secure stringify of JSON Object

support BigInt since v5.17.1

  • Since: 5.16.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
dataJSON Objectany-true-
covertWhether to convert databooleantrue/falsefalsetrue
  • Returns: string

  • Example:

safeStringify(100)
// "100"

safeStringify(undefined)
// "undefined"

safeStringify(NaN)
// "NaN"

safeStringify(Infinity)
// "Infinity"

safeStringify({ a: undefined, b: NaN, c: Infinity, d: BigInt(Number.MAX_SAFE_INTEGER) + 2n })
// {"a":"undefined","b":"NaN","c":"Infinity","d":"9007199254740993"}
  • Types:
declare function safeStringify(data: any, covert?: boolean): string
getDirParam

Get the URL parameter in the form of a directory

It will be refactored and renamed getDirParams in the next major release.

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlhttp urlobject-true-
  • Returns: object

  • Example:

//
  • Types:
declare interface DirParamType {
  path?: string[]
  host?: string
}

declare function getDirParam(url: string): DirParamType
getQueryParam

Get a single query parameter (behind "#")

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
keykey namestring-true-
urlpass in the url stringstring-falselocation.href
  • Returns: string

  • Example:

getQueryParam('key1')
// key1 => xxx

getQueryParam('key1', 'https://test.com?key1=100#/home?key1=200')
// key1 => 200
  • Types:
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)

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlpass in the url stringstring-falselocation.href
covertConverts a specific string to a corresponding valuebooleantrue/falsefalsefalse
  • Returns: object

  • Example:

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\}
  • Types:
declare function getQueryParams(url?: string, covert?: boolean): Record<string, unknown> | null
getUrlParam

Get a single URL parameter (from the "location.search", before "#")

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
keykey namestring-true-
urlpass in the url stringstring-falselocation.href
  • Returns: string

  • Example:

getUrlParam('key1')
// key1 => xxx

getUrlParam('key1', 'https://test.com?key1=100#/home?key1=200')
// key1 => 100
  • Types:
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)

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlpass in the url stringstring-falselocation.href
covertConverts a specific string to a corresponding valuebooleantrue/falsefalsefalse
  • Returns: object

  • Example:

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\}
  • Types:
declare function getUrlParams(url?: string, covert?: boolean): Record<string, unknown> | null
getCache

Get the cache, if the deposited is Object, the retrieved is also Object, no need to convert again

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecache key namestring-true-
  • Returns: any

  • Example:

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') // 100
getCache('data2') // {a:10}
getCache('data3') // null

getCache('data4') // null
  • Types:
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

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecache key namestring-true-
valuecache data, can be passed directly into Objectany-true-
secondscache time (seconds)number-false-
  • Returns: void

  • Example:

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') // 100
getCache('data2') // {a:10}

setTimeout(() => {
  getCache('data2') // null
}, 15000)
  • Types:
declare function setCache<T = unknown>(name: string, value: T, seconds?: number | string): void
delCache

Delete localStorage

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecache key namestring-true-
  • Returns: void

  • Example:

delCache('data')
  • Types:
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

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namesession key namestring-true-
  • Returns: any

  • Example:

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
  • Types:
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

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namesession key namestring-true-
valuesession data, can be passed directly into Objectany-true-
secondssession time (seconds)number-false-
  • Returns: void

  • Example:

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') // 100
getSession('data2') // {a:10}

setTimeout(() => {
  getSession('data2') // null
}, 15000)
  • Types:
declare function setSession<T = unknown>(name: string, value: T, seconds?: number | string): void
delSession

Delete sessionStorage

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namesession key namestring-true-
  • Returns: void

  • Example:

delSession('data')
  • Types:
declare function delSession(name: string): void
getCookie

Get cookie by name

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecookie key namestring-true-
  • Returns: any

  • Example:

getCookie('data1') // 100
  • Types:
declare function getCookie(name: string): string
getCookies

Get all cookies

  • Since: 5.6.0

  • Arguments: 'none'

  • Returns: object

  • Example:

getCookies()
// { token: 'xxx', name: 'saqqdy' }
  • Types:
declare function getCookies(): Record<string, string>
setCookie

Set cookie

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecookie key namestring-true-
valuecookie data, can be passed directly into Objectany-true-
secondscookie time (seconds)number-false-
pathcookie pathstring-false/
samesiteSameSite typestringStrict/Lax /NonefalseNone
  • Returns: void

  • Example:

import { getCookie, setCookie } from 'js-cool'

const data1 = 100
const data2 = 200

setCookie('data1', data1)
setCookie('data2', data2, 10)

getCookie('data1') // 100
getCookie('data2') // 200

setTimeout(() => {
  getCookie('data2') // null
}, 15000)
  • Types:
declare function setCookie<T extends string | number | boolean>(
  name: string,
  value: T,
  seconds: string | number,
  path?: string,
  samesite?: boolean
): void
delCookie

Delete cookie

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
namecookie key namestring-true-
  • Returns: void

  • Example:

delCookie('data')
  • Types:
declare function delCookie(name: string): void

Base64 & UTF8

encodeBase64

convert strings, numbers to base64

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputthe string to be encodedstring/number-true-
  • Returns: void

  • Example:

encodeBase64('data')
  • Types:
declare function encodeBase64(name: string): string
decodeBase64

base64 decoding

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputthe string to be decodedstring/number-true-
  • Returns: void

  • Example:

decodeBase64('data')
  • Types:
declare function decodeBase64(name: string): string
encodeUtf8

convert strings, numbers to utf8

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputthe string to be encodedstring/number-true-
  • Returns: void

  • Example:

encodeUtf8('data')
  • Types:
declare function encodeUtf8(name: string): string
decodeUtf8

utf8 decoding

  • Since: 1.0.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputthe string to be decodedstring/number-true-
  • Returns: void

  • Example:

decodeUtf8('data')
  • Types:
declare function decodeUtf8(name: string): string

Events

stopBubble

stop bubbling

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
edom's event objectEvent-true-
  • Returns: boolean

  • Example:

stopBubble(event)
  • Types:
declare function stopBubble(e: Event): boolean
stopDefault

stop default events

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
edom's event objectEvent-true-
  • Returns: boolean

  • Example:

stopDefault(event)
  • Types:
declare function stopDefault(e: Event): boolean
addEvent

event delegate, support multiple delegates

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
elementjs dom objectHTMLElement-true-
typeThe type of the event. No need to add onstring-true-
handlerCallback methodfunction-true-
  • Returns: void

  • Example:

addEvent(document, 'click', functionName)
  • Types:
declare function addEvent(element: AnyObject, type: string, handler: AnyFunction): void
removeEvent

removeEvent removes the event delegate created by addEvent

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
elementjs dom objectHTMLElement-true-
typeThe type of the event. No need to add onstring-true-
handlerCallback methodfunction-true-
  • Returns: void

  • Example:

removeEvent(document, 'click', functionName)
  • Types:
declare function removeEvent(element: AnyObject, type: string, handler: AnyFunction): void
getScrollPosition

Get slide to top and bottom return 'top' 'bottom', recommend using limit flow

  • Since: 1.0.2

  • Arguments: none

  • Returns: 'top' | 'bottom' | undefined

  • Example:

getScrollPosition() // ‘bottom’
  • Types:
declare function getScrollPosition(): string | void

Utilities

nextIndex

return the next zIndex value

change mix defaults to 0

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
minminimum valuenumber-false0
maxmaximum valuenumber-false-
  • Returns: number

  • Example:

nextIndex() // 1

nextIndex(1000) // 1001

nextIndex(10, 100) // 100
  • Types:
declare function nextIndex(min?: number, max?: number): number
nextVersion

return the next version, Only version types with no more than 3 digits are supported. (Follow the npm version rules)

  • Since: 5.10.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
versionversion(like: 1.0.0)string-true-
typeversion typemajor | minor | patch | premajor | preminor | prepatch | prerelease-falsepatch
preidprerelease idstring-false''
  • Returns: string

  • Example:

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
  • Types:
declare function nextVersion(
  version: string,
  type?: 'major' | 'minor' | 'patch' | 'premajor' | 'preminor' | 'prepatch' | 'prerelease',
  preid?: string
): string
punctualTimer

punctual setInterval

  • Since: 5.18.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
handlerA function to be executed after the timer expires.function-true-
delayThe 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.number-true-
...argsAdditional arguments which are passed through to the function specified by handler.any[]-false-
  • Returns: void

  • Example:

const printDate = () => console.log(new Date())
punctualTimer(printDate, 1000)
  • Types:
declare function punctualTimer<TArgs extends any[]>(
  handler: (args: void) => void,
  delay: number,
  [...args]?: TArgs
): void
declare function punctualTimer<TArgs extends any[]>(
  handler: (...args: TArgs) => void,
  delay: number,
  [...args]?: TArgs
): void
promiseFactory

Convert an object to a promise like api

  • Since: 5.10.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
originaloriginal objectobject-true-
resolverresolver functionFunction-true-
  • Returns: T & PromiseLike<T>

  • Example:

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
  • Types:
declare function promiseFactory<T extends object>(
  original: T,
  resolver: () => Promise<any>
): T & PromiseLike<T>
fixNumber

truncate a few decimal places, not 0 for shortage

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
numberthe number of digits to be processednumber/string-true-
nthe number of decimal places to keepnumber-false2
  • Returns: string | number

  • Example:

fixNumber('100.888')
// 100.88

fixNumber('100.8', 2)
// 100.8

fixNumber('100.8888', 3)
// 100.888
  • Types:
declare function fixNumber(number: string | number, n?: number): number
mapTemplate

Replacing specific data in a template string, support ${xxxx} {{xxxx}} and {xxxx}

  • Since: 5.9.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
tmpTemplate stringstring-true-
dataTemplate data of map functionFunction| Object-true-
  • Returns: string

  • Example:

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 tmp1 = "My name is {{name}}, I'm {{age}} years old."
mapTemplate(tmp1, {
  name: 'saqqdy',
  age: 18
})
// My name is saqqdy, I'm 18 years old.
  • Types:
declare function mapTemplate(
  tmp: string,
  data: ((value: string) => unknown) | Record<string, unknown>
): string
extend

deep copy & merge objects

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetboolean or array or objectboolean/ArrayOneMore<ExtendData>-true-
...argsarray or objectArrayOneMore<ExtendData>-true-
  • Returns: array | object

  • Example:

extend(true, {}, {})
  • Types:
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>
clone

deep copy (Buffer, Promise, Set, Map are not supported)

  • Since: 5.15.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
sourcesource objectany-true-
  • Returns: object

  • Example:

const source = { a: 100, reg: /\d+/g, arr: [1, 2] }
const res = clone(source)
// { a: 100, reg: /\d+/g, arr: [1, 2] }
  • Types:
declare function clone<T = any>(parent: T): T
delay

anti-dither throttling

  • Since: 1.0.2

  • Arguments: none

  • Returns: void

  • Example:

const delay = new Delay()

delay.register('key', () => {
  //
})
  • Types:
declare function delay(): {
  map: any
  register(id: string, fn: AnyFunction, time: number, boo: boolean): void
  destroy(id: string): void
}
getType

Get the target type

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targetany targetany-true-
  • Returns: string

  • Example:

getType({}) // object
getType([]) // array
getType(new Promise()) // promise
getType(new Date()) // date
getType(async () => {}) // function
getType(navigator) // navigator
getType(global) // global
getType(window) // window
getType(Symbol('')) // symbol
  • Types:
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'
getFileType

Determine file type based on link suffix

  • Since: 5.11.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlfile urlstring-true-
  • Returns: object

  • Example:

getFileType('/name.png')
// { "suffix": "png", "type": "image" }

getFileType('/name.PDF')
// { "suffix": "pdf", "type": "pdf" }

getFileType('/name.xyz')
// { "suffix": "xyz", "type": "other" }
  • Types:
declare function getFileType(url: string): {
  suffix: string
  type: 'audio' | 'video' | 'image' | 'other' | 'word' | 'txt' | 'excel' | 'pdf' | 'ppt' | 'zip'
}
sorter

Sorter factory function

  • Since: 5.14.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
localesA string with a BCP 47 language tag, or an array of such stringsstring Array-false-
optionsAn object adjusting the output format.Intl.CollatorOptions-false-
  • Returns: Function

  • Example:

const items = ['啊我', '波拉', 'abc', 0, 3, '10', ',11', 13, null, '阿吧', 'ABB', 'BDD', 'ACD', 'ä']

items.sort(
  sorter('zh-Hans-CN', {
    ignorePunctuation: true,
    sensitivity: 'variant',
    numeric: true
  })
)
// [ 0, 3, "10", ",11", 13, "ä", "ABB", "abc", "ACD", "BDD", null, "阿吧", "啊我", "波拉" ]
  • Types:
declare function sorter(
  locales?: string | string[],
  options?: Intl.CollatorOptions
): <T = string, P = string>(a: T, b: P) => number
sortPinyin

Sort Chinese by Chinese phonetic alphabet

  • Since: 5.14.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
aThe first element for comparison.any-true-
bThe second element for comparison.any-true-
optionsAn object adjusting the output format.Intl.CollatorOptions-false-
  • Returns: number

  • Example:

const items = ['啊我', '波拉', 'abc', 0, 3, '10', ',11', 13, null, '阿吧', 'ABB', 'BDD', 'ACD', 'ä']

items.sort(sortPinyin)
// [ ",11", 0, "10", 13, 3, "ä", "ABB", "abc", "ACD", "BDD", null, "阿吧", "啊我", "波拉" ]

items.sort((a, b) => sortPinyin(a, b, { ignorePunctuation: true, numeric: true }))
// [ 0, 3, "10", ",11", 13, "ä", "ABB", "abc", "ACD", "BDD", null, "阿吧", "啊我", "波拉" ]
  • Types:
declare function sortPinyin<T = string, P = string>(
  a: T,
  b: P,
  options?: Intl.CollatorOptions
): number
cleanData

Data cleaning methods

  • Since: 1.0.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
datathe object to be cleanedobject-true-
mapthe data queue to be cleaned, can be passed as array or objectarray/object-true-
nullFixthe value returned if there is no corresponding property, the default does not return the propertyany-false-
  • Returns: any

  • Example:

//
  • Types:
declare function cleanData(data: any, map: any[] | AnyObject, nullFix?: any): any
download

Several ways of file downloading:

  1. For file formats that some browsers do not recognize. Enter the file URL in the address bar, window.location.href = URL, window.open(URL);
  2. using a tag download attribute (or js create a tag);
  3. browser-recognizable pdf, txt files, back-end compatible with handling attachment;
  4. add token in the header for authenticated download, use XmlHttpRequest to want to backend to launch the request
  • Since: 1.0.5

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlurl linkstring-true-
filenamefile namestring-true-
typedownload typestringhref/open/download/requestfalsedownload
  • Returns: void

  • Example:

download('https://unpkg.com/browse/js-cool@5.2.0/dist/index.global.prod.js')
  • Types:
declare function download(url: string, filename: string, type?: string): void
searchObject

tree object depth lookup

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
treetree objectarray/object-true-
expressionrequired Query methodany-true-
keySetoptional Default subclass name, query nameSearchKeySet-true-
numberoptional Number of lookups, if not passed, query allnumber-false-
  • Returns: any

  • Example:

//
  • Types:
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)

  • Since: 1.0.6

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlhttp urlstring-true-
  • Returns: boolean | undefined

  • Example:

openUrl('https://www.saqqdy.com/js-cool')
  • Types:
declare function openUrl(url: string): void
copy

copy to clipboard

  • Since: 5.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
valueany valueany-true-
  • Returns: boolean | undefined

  • Example:

copy('10000')
  • Types:
declare function copy(value: string): boolean | undefined
toThousands

Digital thousandths division

  • Since: 3.0.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
numthe numberstring/number-true-
  • Returns: string

  • Example:

toThousands(10000) // '10,000'
  • Types:
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

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrthe target arrayarray-true-
fnthe judgment methodfunction-true-
  • Returns: boolean

  • Example:

all([4, 2, 3], x => x > 1)
// true
  • Types:
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

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrthe target arrayarray-true-
fnthe judgment methodfunction-true-
  • Returns: boolean

  • Example:

any([0, 1, 2, 0], x => x >= 2)
// true
  • Types:
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() // '4222fcfe-5721-4632-bede-6043885be57d'
  • Types:
declare const uuid: () => string
CSVToArray

Converts a comma-separated string of values (CSV) to a 2D array.

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
datacsv datastring-true-
delimiterdelimiterstring-false','
omitFirstRowthe first row is the table header databoolean-falsefalse
  • Returns: string

  • Example:

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']]`
  • Types:
declare const CSVToArray: (data: string, delimiter?: string, omitFirstRow?: boolean) => string[][]
arrayToCSV

Converts a two-dimensional array to a comma-separated string of values (CSV).

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrjson dataarray-true-
delimiterdelimiterstring-false','
  • Returns: string

  • Example:

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'
  • Types:
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.

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
datacsv datastring-true-
delimiterdelimiterstring-false','
  • Returns: string

  • Example:

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'}]`
  • Types:
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.

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrjson dataarray-true-
columnsthe specified columnsarray-true-
delimiterdelimiterstring-false','
  • Returns: string

  • Example:

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"'
  • Types:
declare const JSONToCSV: (arr: any[], columns: any[], delimiter?: string) => string
RGBToHex

Converts RGB component values to color codes.

  • Since: 1.0.9

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
rthe 1st value of RGBnumber-true-
gRGB's 2nd valuenumber-true-
bRGB's 3nd valuenumber-true-
  • Returns: string

  • Example:

RGBToHex(255, 165, 1) // 'ffa501'
  • Types:
declare const RGBToHex: (r: number, g: number, b: number) => string
intersect

Find the intersection of multiple arrays

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
...arrarray targetsarray-true-
  • Returns: array

  • Example:

intersect([1, 2], [2, 3, 4], [2, 8], [2, '33']) // [2]
  • Types:
declare function intersect<T = unknown>(...args: T[][]): T[]
union

Find the concatenation of multiple arrays

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
...arrarray targetsarray-true-
  • Returns: array

  • Example:

union([1, 2], [2, '33']) // [1, 2, '33']
  • Types:
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

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
...arrarray targetsarray-true-
  • Returns: array

  • Example:

minus([1, 2], [2, '33'], [2, 4]) // [1]
  • Types:
declare function minus<T = unknown>(...args: T[][]): T[]
complement

Find the complement of multiple arrays

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
...arrarray targetsarray-true-
  • Returns: array

  • Example:

complement([1, 2], [2, '33'], [2]) // [1, '33']
  • Types:
declare function complement<T = unknown>(...args: T[][]): T[]
contains

Whether the array contains the specified element

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrarray targetarray-true-
itemany array memberany-true-
  • Returns: boolean

  • Example:

contains([1, 2], 2) // true
contains([1, 2], 3) // false
  • Types:
declare function contains(arr: any[], item: any): boolean
unique

Array de-duplication

  • Since: 2.2.1

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
arrarray targetarray-true-
  • Returns: array

  • Example:

unique([1, 2, 2, '33']) // [1, 2, '33']
  • Types:
declare function unique<T = unknown>(arr: T[]): T[]
fillIPv6

ipv6 address completion

  • Since: 2.2.2

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
ipip addressstring-true-
  • Returns: string

  • Example:

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'
  • Types:
declare function fillIPv6(ip: string): string
getProperty

Get array, object property values based on path string

v5.19.0 support defaultValue

  • Since: 2.2.4

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targettarget array, objectarray/object-true-
propquery target, can pass functionstring/function-true-
defaultValuedefault valueany-false-
  • Returns: any

  • Example:

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
  • Types:
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
setProperty

Set array, object property values based on path string

  • Since: 2.7.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
targettarget array, objectarray/object-true-
propset target, support function, 'a' | 'a[1].c'string/function-true-
valuevalueany-true-
  • Returns: any

  • Example:

const target = {
  a: 1,
  b: [
    {
      c: 2
    }
  ]
}
setProperty(target, 'a', 2)
setProperty(target, 'b[0].c', 3)
setProperty(target, () => 'a', 100)
  • Types:
declare function setProperty(
  target: any,
  prop:
    | string
    | {
        (): string
      },
  value: any
): any
loadSource

load resources dynamically, support js, images, css links, css style strings

  • Since: 2.8.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urllink to the resource, type must be passed when passing in styleStringstring-true-
optionsparameters: attrs, props, forceSourceOptions-false-
  • Returns: boolean | imageUrl

  • Example:

loadSource('/source/url', options)
  • Types:
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

  • Since: 2.8.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlresource urlstring-true-
optionsparameters: attrs, props, forceCssOptions-false-
  • Returns: boolean

  • Example:

mountCss('/source/url', options)
  • Types:
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

  • Since: 2.8.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlresource urlstring-true-
optionsparameters: attrs, props, forceImgOptions-false-
  • Returns: boolean | imageUrl

  • Example:

mountImg('/source/url', options)
  • Types:
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

  • Since: 2.8.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlresource urlstring-true-
optionsparameters: attrs, props, forceJsOptions-false-
  • Returns: boolean

  • Example:

mountJs('/source/url', options)
  • Types:
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

  • Since: 2.8.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
urlresource urlstring-true-
optionsparameters: attrs, props, forceStyleOptions-false-
  • Returns: boolean

  • Example:

mountStyle('/source/url', options)
  • Types:
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

  • Since: 5.5.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
imagesimages urlstring array-true-
  • Returns: void

  • Example:

preloader('path/of/image')

preloader(['path/of/image'])
  • Types:
declare function preloader(images: string): HTMLImageElement

declare function preloader(images: string[]): Record<string, HTMLImageElement>
waiting

v5.8.1 Support throw on timeout

waiting for a while

  • Since: 5.5.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
millisecondswaiting time (milliseconds)number-true-
throwOnTimeoutthrow on timeoutboolean-falsefalse
  • Returns: Promise<void>

  • Example:

waiting(2000)

await waiting(2000, true)
// reject
  • Types:
declare function waiting(milliseconds: number, throwOnTimeout?: boolean): Promise<void>
awaitTo

Async await wrapper for easy error handling

v5.7.0 Extend awaitTo to support passing in multiple promises

  • Since: 5.2.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
promisepromise functionPromise Promise[]-true-
...promisesPromise rest paramsPromise[]-false-
  • Returns: [Error, undefined] or [null, data | data[]]

  • Example:

import { awaitTo as to } from 'js-cool'

// 1. simple use
const [err, data] = await to(new Promise())
if (err) {
  // handle request error
}

// 2. Pass in multiple promises
const [err, data] = await to(promise1, promise2)
// or
const [err, data] = await to([promise1, promise2])
  • Types:
declare function awaitTo<T, E = Error>(promise: Promise<T>): Promise<[E, undefined] | [null, T]>

declare function awaitTo<P extends readonly unknown[] | [], E = Error>(
  promise: PromiseAll<P>
): Promise<[E, undefined] | [null, P]>

declare function awaitTo<T, P extends readonly unknown[] | [], E = Error>(
  promise: Promise<T>,
  ...promises: PromiseAll<P>
): Promise<[E, undefined] | [null, [T, ...P]]>

export declare type PromiseAll<P extends readonly unknown[] | []> = {
  -readonly [K in keyof P]: Promise<P[K]>
}

Blob arrayBuffer base64 file blobUrl

arrayBufferToBase64

arrayBuffer to base64

v5.19.1 remove default params of mime

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputarrayBuffer dataArrayBuffer-true-
mimeimage mimeString-false-
  • Returns: String

  • Example:

arrayBufferToBase64(arrayBuffer, 'image/png')
// data:image/png;base64,xxxxxxxxxxxx

arrayBufferToBase64(arrayBuffer)
// xxxxxxxxxxxx
  • Types:
declare function arrayBufferToBase64(input: ArrayBuffer, mime?: string): string
arrayBufferToBlob

arrayBuffer to blob

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputarrayBuffer dataArrayBuffer-true-
mimeimage mimeString-falseimage/png
  • Returns: Blob

  • Example:

arrayBufferToBlob(arrayBuffer, 'image/png')
// Blob
  • Types:
declare function arrayBufferToBlob(input: ArrayBuffer, mime?: string): Blob
base64ToArrayBuffer

base64 to arrayBuffer

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputbase64 stringString-true-
  • Returns: ArrayBuffer

  • Example:

base64ToArrayBuffer(base64)
// ArrayBuffer
  • Types:
declare function base64ToArrayBuffer(input: string): ArrayBuffer
base64ToBlob

base64 to blob

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputbase64 stringString-true-
  • Returns: Blob

  • Example:

base64ToBlob(base64)
// Blob
  • Types:
declare function base64ToBlob(input: string): Blob
base64ToFile

base64 to file

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputbase64 stringString-true-
fileNamefile nameString-true-
  • Returns: File

  • Example:

base64ToFile(base64, 'image.png')
// File
  • Types:
declare function base64ToFile(input: string, fileName: string): File
blobToArrayBuffer

blob to arrayBuffer

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputblob dataBlob-true-
  • Returns: ArrayBuffer

  • Example:

blobToArrayBuffer(blob).then(data => {
  // ArrayBuffer
})
  • Types:
declare function blobToArrayBuffer(input: Blob): Promise<ArrayBuffer | null>
blobToBase64

blob to base64

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputblob dataBlob-true-
  • Returns: String

  • Example:

blobToBase64(blob).then(data => {
  // data:image/png;base64,xxxxxxxxxxxx
})
  • Types:
declare function blobToBase64(input: Blob): Promise<string | null>
blobToUrl

blob to url

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputblob dataBlob-true-
  • Returns: Object

  • Example:

blobToUrl(blob)
// blob:xxxxxxx
  • Types:
declare function blobToUrl(input: Blob): string
fileToBase64

file to base64

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputfile dataFile-true-
  • Returns: String

  • Example:

fileToBase64(file).then(data => {
  // data:image/png;base64,xxxxxxxxxxxx
})
  • Types:
declare function fileToBase64(input: File): Promise<string | null>
svgToBlob

svg to blob

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputsvg stringString-true-
  • Returns: Blob

  • Example:

svgToBlob(svg)
// Blob
  • Types:
declare function svgToBlob(input: string): Blob
urlToBlob

url to blob

  • Since: 5.13.0

  • Arguments:

ParametersDescriptionTypeOptionalRequiredDefault
inputurlString-true-
  • Returns: Blob

  • Example:

urlToBlob(url).then(blob => {
  // Blob
})
  • Types:
declare function urlToBlob(input: string): Promise<Blob | null>

Support & Issues

Please open an issue here.

License

MIT

Keywords

FAQs

Package last updated on 27 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc