jcommon

JavaScript common pure function library (current version is used in the project, future updates will be forward compatible) continues to enrich…

Introduction to the

In daily work, we often use someDate formatting.Url-related operations.Browser Type Judgment.Common validation formatsAnd so on functions, although most of them can be found only by Google/Baidu, but most of them have some problems, so I sorted out the online and their usual use of the tool class, convenient for everyone to use in the future, improve the development efficiency.

The installation

NPM

NPM installation is recommended when JCommon is applied to large projects. NPM works well with the WebPack module packer. Complete on-demand references.

# The latest stable version
$ npm install jcommon

Check whether a datatype is an object.
import { isObject, isArray } from 'jcommon'
Copy the code

Project characteristics

  • Full reference on demand, we only export pure functions
  • Instead of exporting a whole module from a traditional JS library (moment, utils,…
  • NPM installation is supported
  • Support for script tags directly introduced (consider using a global module approach, jcommon, to avoid global namespace contamination)
  • Continue to enrich the method library
  • Integrate some common node methods (fully on demand, you don’t have to worry about library size)
  • Support and be friendly to TS

API directory

Array method

  • DoubleRanking handles two levels of sorting of complex arrays (one in custom order and two in reverse order)
  • RandomData generates randomData
  • ArrByObj (used to handle enumeration conversions returned in the background, often used in work)
  • ArrayToTreeData One-dimensional array to multidimensional tree structure data

Browser dependent

  • GetBrowserInfo Gets browser-related information

Data persistence, caching

  • RemoveStorage delete
  • SaveStorage save
  • GetStorage access
  • IsSupportStorage Whether local is supported

  • GetCookie Obtains the cookie value

Time correlation

  • DateInterval Gets the interval between two times
  • AddZero string complement 0, currently available to dateFormat
  • DateFormat time conversion (currently supports year, month, day, hour, minute, second, week)
  • DateMonthDays Days of the current month
  • TimeFormat Time customization

Several processing phase

  • ScopeRandom Range is a random integer

User device dependent (client system)

  • OsInfo Obtains information about the user’s system platform

Mobile correlation

  • IsQQ is the QQ platform
  • IsWX is a wechat platform
  • Operattelecom gets the phone operator
  • IsAndroidMobileDevice Is an Android device
  • IsAppleMobileDevice Indicates whether the device is an Apple device

Object correlation (Object handling)

  • GetV gets multi-level data to avoid errors (super useful)
  • Clone object clone (only traversable properties < common >)
  • The existing properties of the mergeObj deep merge object (currently used to merge the system configuration file app-data.json) are not overwritten by default

String handling correlation

  • Trim Removes whitespace from string (default)
  • GetSexByIdNO Indicates the gender of id number resolution
  • GetBirthdatByIdNo Id number parsing birth date
  • HideIdNum Hides the ID number
  • UniqueId Time stamp of the random number
  • AgeFormat Birth Date Calculated age

Url processing correlation

  • GetUrlQuery gets a parameter in the browser URL
  • ObjByUrlStr formats the GET request header
  • UrlByObj handles the conversion of url arguments (window.location.search) to {key: value}

General tool method

  • The debounce function defends the same event more than once in a short period of time.
  • Throttling < means firing events continuously but executing the function only once in n seconds. That is, two executions within 2n seconds… . Throttling literally dilutes the execution frequency of the function. >

Check the related

  • IsUserId ID card number verification (accurate)
  • IsType determines data types accurately
  • IsString Identifies the String type
  • IsNumber Checks the Number type
  • IsBoolean Indicates the Boolean type
  • IsUndefined Indicates the type of Undefined
  • IsNull Determines the Null type
  • IsFunc determines the Function type
  • IsDate Indicates the Date type
  • IsArray Determines the Array type
  • IsReg Determines the RegExp type
  • IsError Indicates the Error type
  • IsObject Identifies the Object type
  • Verify the isPhone number
  • IsEmail Indicates whether the verification is an email address

API specification

getBrowserInfo

Get browser-related information

wuxh
 * @Date: 2020- 05- 06 11:53:35
 * @param {} 
 * @return: Object
 * @example: 
  getBrowserInfo()
  => {name: "Chrome".version: "81.0.4044.129"}
Copy the code

doubleRanking

Handles two levels of sorting of complex arrays (one in custom order and two in reverse order)

wuxh 
 * @Date: 2020- 05- 06 11:37:17* @param {arr} the array that needs to be processed * @param {options} Additional arguments * @return: {Array} * @example: doubleRanking([{education: 'bachelor'.age: 26},
        {education: 'primary'.age: 25},
        {education: 'bachelor'.age: 24},
        {education: 'primary'.age: 23}, {filterRuleKey: 'education'.rule: ['primary'.'bachelor'].sortKey: 'age'.sortOrder: 1}) => [{education: 'primary'.age: 24},
        {education: 'primary'.age: 26}
        {education: 'bachelor'.age: 23},
        {education: 'bachelor'.age: 25},]Copy the code

randomData

Generate random data

wuxh
 * @Date: 2020- 05- 06 11:41:08* @param {num} Number * @param {arr} Keys of each element object * @return: {Array} 
 * @example: 
  randomData(2['name'.'value']) = > [{"name":"name323"."value":"value699"}, {"name":"name573"."value":"value393"}]
Copy the code

arrByObj

Numeric to object (used to handle enumeration conversions returned in the background, common in work)

wuxh
 * @Date: 2020- 05- 06 11:51:49* @param {arr} the array to be converted * @param {key} needs to be the key of the converted object * @param {v} the value of the object, the default is each element of the array as the value * @return: Object
 * @example: 
  const arr = arr = [{name: 111.value: 222}, {name: 333.value:444}]
  arrByObj(arr, 'name') = > {"111": {"name":111."value":222},"333": {"name":333."value":444}}
  arrByObj(arr, 'name', value)   =>    {"111":222."333":444}
Copy the code

arrayToTreeData

One-dimensional array to multidimensional tree structure data

wuxh
 * @Date: 2020- 06- 22 17:54:54* @param {arr} one-dimensional array * @param {id} root node ID * @return: Array
 * @example:
  const arr = [{id: 1.parentId: 2.name: 111}, {id: 3.parentId: 1.name: 222}]
  arrayToTreeData(arr, 2) = > [{id: 1.parentId: 2.name: 111.children: [{id: 3.parentId: 1.name: 222}]}]
Copy the code

removeStorage

delete

wuxh
 * @Date: 2020- 05- 06 11:56:29
 * @param {key}
 * @return: undefined
 * @example: 
  removeStorage('test') = >undefined
Copy the code

saveStorage

save

wuxh
 * @Date: 2020- 05- 06 11:56:29
 * @param {key}
 * @param {value}
 * @param {isJson}
 * @return: undefined
 * @example: 
  saveStorage('test'.'001') = >undefined
Copy the code

getStorage

To obtain

wuxh
 * @Date: 2020- 05- 06 12:00:37
 * @param {key}
 * @return: String
 * @example: 
  getStorage('test') = >'001'
Copy the code

isSupportStorage

Whether local is supported

wuxh
 * @Date: 2020- 05- 06 12:01:43
 * @param 
 * @return: Boolean
 * @example: 
  isSupportStorage()
  => true
Copy the code

getCookie

Get the cookie value

wuxh
 * @Date: 2020- 06- 09 09:28:06
 * @param {type} 
 * @return: string
 * @example: 
  getCookie('name') = >123
Copy the code

dateInterval

Gets the interval between two times

wuxh
 * @Date: 2020- 05- 06 12:04:39
 * @param {st}
 * @param {et}
 * @return: String
 * @example: 
  dateInterval(new Date().getTime(), 1589661011714) = >11day13hours46minutes21secondsCopy the code

addZero

String complement 0, currently available to dateFormat

wuxh
 * @Date: 2020- 05- 11 14:01:20* @param {v} Data to be processedString | Number* @param {size} The expected total number of digits * @return: String
 * @example: 
  addZero(12.1) = >12
  addZero(12.2) = >12
  addZero(12.3) = >012
Copy the code

dateFormat

Time conversion (currently supports year, month, day, hour, minute, second, week)

wuxh
 * @Date: 2020- 05- 06 12:05:28
 * @param {date}
 * @param {formatStr}
 * @return: String
 * @example: 
  dateFormat(new Date(), 'YY-MM-DD HH:II:SS week W') = >"Current time 20-05-11 14:07:02 Monday"
Copy the code

dateMonthDays

Gets the number of days in the current month

wuxh
 * @Date: 2020- 05- 06 12:06:24
 * @param {str}
 * @return: Number
 * @example: 
  dateMonthDays('2020-05-06') = >31
Copy the code

timeFormat

Time personalized output function

wuxh
 * @Date: 2020- 06- 09 09:44:23
 * @param {type} 
 * @return: string
 * @example: 
  1, <60S, displayed as "just"2, > =1min && < 60 min, display the time difference with the current"XXMinutes ago"3, >= 60min && < 1day, displays the difference with the current time "todayXX:XX"4, >= 1day && < 1year, display the date"XXmonthXXdayXX:XX"5, >TimeFormat (new Date()) => 'just'Copy the code

osInfo

Obtain user system platform information

wuxh
 * @Date: 2020- 05- 06 12:07:03
 * @param {e}
 * @return: {os: "mac".version: "10.15.3"}
 * @example: 
  osInfo()
  => {os: "mac".version: "10.15.3"}
Copy the code

scopeRandom

Range random integer

wuxh
 * @Date: 2020- 05- 06 12:09:34
 * @param {str}
 * @param {end}
 * @return: Number
 * @example: 
  scopeRandom(1.10) = >3
Copy the code

isQQ

QQ platform

wuxh
 * @Date: 2020- 05- 06 12:10:41
 * @param
 * @return: Boolean
 * @example: 
  isQQ()
  => false
Copy the code

isWX

Is it wechat

wuxh
 * @Date: 2020- 05- 06 12:10:41
 * @param
 * @return: Boolean
 * @example: 
  isWX()
  => false
Copy the code

operattelecom

Obtaining a Mobile carrier

wuxh
 * @Date: 2020- 05- 06 12:11:39
 * @param {}
 * @return: 'mobile' | 'telecommunications' | 'unicom' | 'unknown'
 * @example: 
  operattelecom('13419595634') = > moveCopy the code

isAndroidMobileDevice

Whether it is an Android device

wuxh
 * @Date: 2020- 06- 09 09:31:04
 * @param {type} 
 * @return: boolean
 * @example: 
  isAndroidMobileDevice() => false
Copy the code

isAppleMobileDevice

Is it an Apple device?

wuxh
 * @Date: 2020- 06- 09 09:31:55
 * @param {type} 
 * @return: boolean
 * @example: 
  isAppleMobileDevice() => true
Copy the code

getV

Get multiple levels of data to avoid errors (super useful)

wuxh
 * @Date: 2020- 05- 06 12:13:59* @param {... any} args * @return: any
 * @example: 
  getV(' ', {name: {children: 123}}, 'name'.'children') = >123
Copy the code

clone

Object cloning (only traversable properties < common >)

wuxh
 * @Date: 2020- 05- 06 12:14:45
 * @param {obj}
 * @return: Object
 * @example: 
  clone({name: 123= > {})name: 123}
Copy the code

mergeObj

The existing properties of the deep merge object (currently used to merge the system configuration file app-data.json) are not overwritten by default

wuxh
 * @Date: 2020- 05- 06 12:15:30* @param {oldObj} * @param {newObj} * @param {keys} enforces an array of keys for an attribute * @return: Object
 * @example:  
  mergeObj({name: 111}, {name:333.value: 222= > {}, [])name: 111.value: 222}
  mergeObj({name: 111}, {name:333.value: 222},'name']) = > {name: 333.value: 222}
Copy the code

trim

Remove string whitespace by default (common)

wuxh
 * @Date: 2020- 05- 06 13:43:52
 * @param {str} String
 * @param {global} Boolean
 * @return: String
 * @example: 
  trim('1 1 1') = >'1 1 1'
  trim('1 1 1'.true) = >'111'
Copy the code

getSexByIdNO

Identity card number parsing gender

wuxh
 * @Date: 2020- 06- 09 09:16:28
 * @param {type} 
 * @return: 'FEMALE''MALE'
 * @example: 
   getSexByIdNO('421182199409274710') => MALE
Copy the code

getBirthdatByIdNo

Id number resolution date of birth

wuxh
 * @Date: 2020- 06- 09 09:17:50
 * @param {type} 
 * @return: string
 * @example: 
  getBirthdatByIdNo('421182199409274710') = >'1994-09-27'
Copy the code

hideIdNum

Hiding id Card Number

wuxh
 * @Date: 2020- 06- 09 09:19:26
 * @param {type} 
 * @return: string
 * @example: 
  hideIdNum('421182199409274710') = >4* * * * * * * * * * * * * * * *0
Copy the code

uniqueId

Random number timestamp

wuxh
 * @Date: 2020- 06- 09 09:47:34
 * @param {type} 
 * @return: string
 * @example: 
  uniqueId() => '1591667193048544'
Copy the code

ageFormat

Date of birth counts age

wuxh
 * @Date: 2020- 06- 09 09:47:34
 * @param {type} 
 * @return: string
 * @example: 
  ageFormat('1994-09-27') = >'25'
  ageFormat('2020-02-27') = >'four months'
  ageFormat('2020-06-02') = >'15 days'
Copy the code

getUrlQuery

Gets a parameter in the browser URL

wuxh
 * @Date: 2020- 05- 06 13:46:28
 * @param {name}
 * @return: String
 * @example: 
  getUrlQuery(age)
  => 25
Copy the code

objByUrlStr

Format the request header for the GET request

wuxh
 * @Date: 2020- 05- 06 13:47:40
 * @param {obj}
 * @return: String
 * @example: 
  objByUrlStr({name: 1.value: 123}) = >"name=1&value=123"
Copy the code

urlByObj

Converts url arguments (window.location.search) to {key: value}

wuxh
 * @Date: 2020- 05- 06 13:48:36
 * @param {params}
 * @return: Object* @example: urlByObj(? ie=UTF- 8 -&wd=asd)
  => {ie: UTF- 8 -.wd: asd}
Copy the code

debounce

Function stabilization < trigger the same event multiple times in a short period of time, only execute the last time >

wuxh
 * @Date: 2020- 05- 06 13:46:28* @param * {func< logical methods that need to be protected >, wait< wait time >, immediate< Boolean, whether to execute immediately >} * @return: String
 * @example: 
  // For example, the search box input needs to be buffered
  // Use the debounce method to generate an anti-shake method
  const search = debounce((value) = > console.log, 1000.false)
  // Bind the generated search method where you need it
  // The func part of your logic will be executed according to the anti-shake parameters you set
  onChange = {search}
Copy the code

throttle

Function throttling < means that events are fired continuously but the function is executed only once in n seconds. That is, two executions within 2n seconds… . Throttling literally dilutes the execution frequency of the function. >

wuxh
 * @Date: 2020- 05- 06 13:46:28* @param {func >, wait< interval >, type<1 | 2 >}
 * @return: String
 * @example: 
  // For example, rolling events need to be throttled
  // Use the debounce method to generate an anti-shake method
  const scroll = throttle((value) = > console.log, 1000.1)
  // Bind the generated search method where you need it
  // The func part of your logic will be executed according to the anti-shake parameters you set
  onScroll = {scroll}
Copy the code

isUserId

Verification of ID card number (accurate)

wuxh
 * @Date: 2020- 05- 06 13:49:58
 * @param {e}
 * @return: String<msg> | Boolean
 * @example: 
  isUserId('421182199409274710') = >' '
  isUserId('421182199409') = >'The ID card number should be 18 digits in length'
Copy the code

isType

Accurately determine data types

wuxh
 * @Date: 2020- 05- 06 13:51:50
 * @param {data} any
 * @param {type} type  'String' | 'Number' | 'Boolean' | 'Undefined' | 'Null' | 'Function' | 'Date' | 'Array' | 'RegExp' | 'Error' | 'Object'
 * @return: Boolean
 * @example: 
  isType(123.'String') = >false
  isType('123'.'String') = >true
Copy the code

isString

Determining the String type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isString(123) = >false
  isString(' ') = >true
Copy the code

isNumber

Determining the Number type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isNumber(123) = >true
  isNumber(' ') = >false
Copy the code

isBoolean

Judge Boolean types

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isBoolean(false) = >true
  isBoolean('false') = >false
Copy the code

isUndefined

Judge Undefined type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isUndefined(undefined) = >true
  isUndefined('undefined') = >false
Copy the code

isNull

Determining the Null type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isNull(null) = >true
  isNull('null') = >false
Copy the code

isFunc

Function type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isFunc((a)= > 123) = >true
  isFunc(123) = >false
Copy the code

isDate

Determine the Date type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isDate((a)= > new Date()) = >false
  isDate(new Date()) = >true
Copy the code

isArray

Checking the Array type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isArray([]) => trueisArray(! []) = >false
Copy the code

isReg

Determine the RegExp type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isReg(new RegExp()) = >trueisReg(! []) = >false
Copy the code

isError

Determining the Error type

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isError(new Error()) = >trueisError(! []) = >false
Copy the code

isObject

Determining the type of Object

wuxh
 * @Date: 2020- 05- 06 13:53:16
 * @param {data} any
 * @return: Boolean
 * @example:
  isObject({}) => trueisObject(! []) = >false
Copy the code

isPhone

Mobile phone number check

wuxh
 * @Date: 2020- 06- 09 09:21:15
 * @param {type} 
 * @return: boolean
 * @example: 
  isPhone('13419595634') = >true
Copy the code

isEmail

Verify whether it is an email address

wuxh
 * @Date: 2020- 06- 09 09:49:29
 * @param {type} 
 * @return: boolean
 * @example: 
  isEmail('[email protected]') = >true
Copy the code

Suggestions, communication, recommendations, feedback

Github.com/wxingheng/j…

Contact me [email protected]