Preface
Sometimes the front-end development will process some data returned from the background, or do some processing according to the data judgment; at this time, it is very necessary to encapsulate some common tool classes;
This paper encapsulates 59 methods according to some commonly used tool classes, of course, there are many less used methods that are not entered in the early stage, and keep up with the new ones in the later stage;
Source address, Utils LAN source address Welcome star!
Use
1. method 1
npm i -S utils-lan import utils from 'utils-lan' console.log(utils.arrJudge(['1','2']))
2. method two
git clone Utils LAN source address Down to import the project;
Recommend a bug management tool to you, please stamp
bug management tools
arr
1.arrAndSet
Union
/** * Array Union, only one dimension array is supported * @param {Array} arrOne * @param {Array} arrTwo */ export const arrAndSet = (arrOne, arrTwo) => { return arrOne.concat(arrTwo.filter(v => !arrOne.includes(v))) }
2.arrIntersection
intersection
/** * Array intersection, only one-dimensional array is supported * @param {Array} arrOne * @param {Array} arrTwo */ export const arrIntersection = (arrOne, arrTwo) => { return arrOne.filter(v => arrTwo.includes(v)) }
3.arrDifference
Difference set
/** * Array difference set, only one-dimensional array is supported * @param {Array} arrOne * @param {Array} arrTwo * eg: [1, 2, 3] [2, 4, 5] The difference set is [1,3,4,5] */ export const arrDifference = (arrOne, arrTwo) => { return arrOne.concat(arrTwo).filter(v => !arrOne.includes(v) || !arrTwo.includes(v)) }
4.arrTwoToArrObj
Combine two arrays into one array object
/** * Two arrays are combined into one object array. Considering the complexity, two one-dimensional arrays are currently supported * @param {Array} arrOne * @param {Array} arrTwo * @param {oneKey} oneKey Optional. If neither is passed, the value of arrOne is used as the key and arrtwo is used as the value * @param {twoKey} twoKey */ export const arrTwoToArrObj = (arrOne, arrTwo, oneKey, twoKey) => { if(!oneKey&&!twoKey){ return arrOne.map((oneKey, i) => ({ [oneKey]:arrTwo[i] })) }else{ return arrOne.map((oneKey, i) => ({ oneKey, twoKey: arrTwo[i] })) } }
5.arrObjSum
Sum of array objects
/** * Sum of array objects * @param {Object} arrObj Array objects * @param {String} key key value corresponding to array */ export const arrObjSum = (obj, key) => { return arrObj.reduce((prev, cur) => prev + cur.key, 0) }
6.arrConcat
Array merging
/** * Array merging, currently merging one dimension * @param {Array} arrOne array * @param {Array} arrTwo array */ export const arrConcat = (arrOne, arrTwo) => { return [...arrOne, ...arrTwo] }
7.arrSum
Array summation
/** * Array summation * @param {Array} arr array */ export const arrSum = arr => { return arr.reduce((prev, cur)=> { return prev + cur }, 0) }
8.arrIncludeValue
Whether the array contains a value
/** * Whether the array contains a value * @param {Array} arr array * @param {} value Value, currently only String,Number,Boolean are supported */ export const arrIncludeValue = (arr, value) => { return arr.includes( value) }
9.arrMax
Array maximum
/** * Array maximum * @param {Array} arr array */ export const arrMax = arr => { return Math.max(...arr) }
10.arrRemoveRepeat
Array weight removal
/** * Array weight removal * @param {Array} arr array */ export const arrRemoveRepeat = arr => { return Array.from(new Set(arr)) }
11.arrOrderAscend
Array sorting
/** * Array sorting * @param {Array} arr array * @param {Boolean} ascendFlag Ascending, default is true */ export const arrOrderAscend = (arr, ascendFlag=true) => { return arr.sort((a, b) => { return ascendFlag ? a - b : b - a }) }
12.arrJudge
Determine whether it is an array
/** * Determine whether it is an array * @param {Array}} arr array */ export const arrJudge = arr => { if (Array.isArray(arr)) { return true } }
check
13.checkNum
Judge whether it is a number
/** * Judge whether it is a number * @param {Number} data */ export const checkNum = data => { const reg = /^\d{1,}$/g if (reg.test(data)) return true }
14.checkLetter
Determine whether it is a letter
/** * Determine whether it is a letter * @param {Number} data */ export const checkLetter = data => { const reg = /^[a-zA-Z]+$/g if (reg.test(data)) return true }
15.checkLowercaseLetter
Determine whether all are lowercase letters
/** * Determine whether all are lowercase letters * @param {Number} data */ export const checkLowercaseLetter = data => { const reg = /^[a-z]+$/g if (reg.test(data)) return true }
16.checkCapitalLetter
Determine whether it is a capital letter
/** * Determine whether it is a capital letter * @param {Number} data */ export const checkCapitalLetter = data => { const reg = /^[A-Z]+$/g if (reg.test(data)) return true }
17.checkNumOrLetter
Determine whether it is a letter or a number
/** * Determine whether it is a letter or a number * @param {Number || String} data Character or number */ export const checkNumOrLetter = data => { const reg = /^[0-9a-zA-Z]*$/g if (reg.test(data)) return true }
18.checkChinese
Judge whether it is Chinese
/** * Judge whether it is Chinese * @param {String} data Chinese */ export const checkChinese = data => { const reg = /^[\u4E00-\u9FA5]+$/g if (reg.test(data)) return true }
19.checkChineseNumberLettter
Determine whether it is Chinese, number or letter
export const checkChineseNumberLettter = data => { const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/g if (reg.test(data)) return true }
20.checkEmail
Determine whether it is email address
/** * Determine whether it is email address * @param {String} data */ export const checkEmail = data => { const reg = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/g if (reg.test(data)) return true }
21.checkTelphone
Determine whether it is a mobile phone number
/** * Judge whether it is a mobile number, as long as it starts from 13, 14, 15, 16, 17, 18, 19 * @param {String} data */ export const checkTelphone = data => { const reg = /^((\+|00)86)?1[3-9]\d{9}$/g if (reg.test(data)) return true }
22.checkUrl
Determine whether it is the correct website
/** * Determine whether it is the correct website * @param {String} url Website */ export const checkUrl = url => { const a = document.createElement('a') a.href = url return [ /^(http|https):$/.test(a.protocol), a.host, a.pathname !== url, a.pathname !== `/${url}` ].find(x => !x) === undefined }
client
23.checkBrowser
/** * Judge it is browser kernel */ export const checkBrowser = () => { const u = navigator.userAgent; const obj = { trident: u.indexOf("Trident") > -1, //IE kernel presto: u.indexOf("Presto") > -1, //opera kernel webKit: u.indexOf("AppleWebKit") > -1, //Apple, Google kernel gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //Firefox kernel } return Object.keys(obj)[Object.values(obj).indexOf(true)] };
24.checkIosAndroidIpad
Judge whether it is terminal type, with IOS, Android and iPad values
/** * Judge whether it is terminal type, with IOS, Android and iPad values */ export const checkIosAndroidIpad = () => { const u = navigator.userAgent; const obj = { ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios terminal android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android terminal or uc browser iPad: u.indexOf("iPad") > -1, //Whether iPad } return Object.keys(obj)[Object.values(obj).indexOf(true)] };
25.checkWeixinQqUc
Determine whether it is wechat, qq or uc
/** * Determine whether it is wechat, qq or uc */ export const checkWeixinQqUc = () => { const u = navigator.userAgent; const obj = { weixin: u.indexOf("MicroMessenger") > -1, //Whether WeChat? qq: u.match(/QQ/i) == "qq"&&!u.indexOf('MQQBrowser') > -1, //Whether QQ uc: u.indexOf('UCBrowser') > -1 } return Object.keys(obj)[Object.values(obj).indexOf(true)] };
26.checkIsIphoneX
Check if it's iPhone
/** * Check if it's iPhone */ export const checkIsIphoneX = () => { const u = navigator.userAgent; const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); if (isIOS && screen.height >= 812) { return true; } };
file
27.fileFormatSize
Format file units
/** * Format file units * @param {String || Number} size File size (kb) */ export const fileFormatSize = size => { var i var unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] for (i = 0; i < unit.length && size >= 1024; i++) { size /= 1024 } return (Math.round(size * 100) / 100 || 0) + unit[i] }
obj
28.objIsEqual
To determine whether two objects are equal, currently only the judgment of simple data type is supported
/** * To determine whether two objects are equal, currently only the judgment of simple data type is supported * @param {Object} oneObj object * @param {Object} twoObj object */ export const objIsEqual = (oneObj, twoObj) => { return JSON.stringify(oneObj) === JSON.stringify(twoObj) }
29.objDeepClone
Object depth clone;
1.JSON.stringify deep clone object;
2. Unable to clone special objects such as function and RegExp;
3. The constructor of the Object will be discarded, and all constructors will point to the Object;
4. The object has a circular reference and an error will be reported
/** * Object depth clone, * JSON.stringify Deep clone object * Cannot clone special objects such as function, RegExp, etc, * The constructor of the Object will be discarded, and all constructors will point to the Object * Object has circular reference, error will be reported * @param {Object} obj Cloned objects */ export const objDeepClone = obj => { return clone(obj) } const isType = (obj, type) => { if (typeof obj !== 'object') return false; // The classic method of judging data type: const typeString = Object.prototype.toString.call(obj); let flag; switch (type) { case 'Array': flag = typeString === '[object Array]'; break; case 'Date': flag = typeString === '[object Date]'; break; case 'RegExp': flag = typeString === '[object RegExp]'; break; default: flag = false; } return flag; }; /** * deep clone * @param {[type]} parent object Objects that need to be cloned * @return {[type]} Objects after deep cloning */ const clone = parent => { // Maintain two arrays of stored loop references const parents = [] const children = [] const _clone = parent => { if (parent === null) return null if (typeof parent !== 'object') return parent let child, proto if (isType(parent, 'Array')) { // Special handling of arrays child = [] } else if (isType(parent, 'RegExp')) { // Special treatment of regular objects child = new RegExp(parent.source, getRegExp(parent)) if (parent.lastIndex) child.lastIndex = parent.lastIndex } else if (isType(parent, 'Date')) { // Special handling of Date objects child = new Date(parent.getTime()) } else { // Working with object prototypes proto = Object.getPrototypeOf(parent) // Using Object.create to cut off the prototype chain child = Object.create(proto) } // Processing circular references const index = parents.indexOf(parent) if (index !== -1) { // If this object exists in the parent array, it means that it has been referenced before, and this object will be returned directly return children[index] } parents.push(parent) children.push(child) for (const i in parent) { // recursion child[i] = _clone(parent[i]) } return child } return _clone(parent) }
storage
30.localStorageSet
localStorage storage
At present, if the object value is a function, RegExp and other special object storage, it will be ignored
/** * localStorage Keep in storage * At present, if the object value is a function, RegExp and other special object storage, it will be ignored * @param {String} key attribute * @param {Object} value value */ export const localStorageSet = (key, value) => { if (typeof (value) === 'object') value = JSON.stringify(value) localStorage.setItem(key, value) }
31.localStorageGet
localStorage get
/** * localStorage Obtain * @param {String} key attribute */ export const localStorageGet = (key) => { return JSON.parse(localStorage.getItem(key)) }
32.localStorageRemove
localStorage removal
/** * localStorage remove * @param {String} key attribute */ export const localStorageRemove = (key) => { localStorage.removeItem(key) }
33.localStorageSetExpire
Local storage fails for a certain period of time
/** * localStorage Failure of storage for a certain period of time * @param {String} key attribute * @param {*} value Storage value * @param {String} expire Expiration time, milliseconds */ export const localStorageSetExpire = (key, value, expire) => { if (typeof (value) === 'object') value = JSON.stringify(value) localStorage.setItem(key, value) setTimeout(() => { localStorage.removeItem(key) }, expire) }
34.sessionStorageSet
sessionStorage storage
/** * sessionStorage Keep in storage * @param {String} key attribute * @param {*} value value */ export const sessionStorageSet = (key, value) => { if (typeof (value) === 'object') value = JSON.stringify(value) sessionStorage.setItem(key, value) }
35.sessionStorageGet
sessionStorage get
/** * sessionStorage Obtain * @param {String} key attribute */ export const sessionStorageGet = (key) => { return JSON.parse(sessionStorage.getItem(key)) }
36.sessionStorageRemove
Sessionstoredelete
/** * sessionStorage delete * @param {String} key attribute */ export const sessionStorageRemove = (key, value) => { sessionStorage.removeItem(key, value) }
37.sessionStorageSetExpire
sessionStorage storage fails for a certain period of time
/** * sessionStorage Failure of storage for a certain period of time * @param {String} key attribute * @param {*} value Storage value * @param {String} expire Expiration time, milliseconds */ export const sessionStorageSetExpire = (key, value, expire) => { if (typeof (value) === 'object') value = JSON.stringify(value) sessionStorage.setItem(key, value) setTimeout(() => { sessionStorage.removeItem(key) }, expire) }
38.cookieSet
cookie storage
/** * cookie Keep in storage * @param {String} key attribute * @param {*} value value * @param String expire Expiration time in days */ export const cookieSet = (key, value, expire) => { const d = new Date() d.setDate(d.getDate() + expire) document.cookie = `${key}=${value};expires=${d.toGMTString()}` }
39.cookieGet
cookie acquisition
/** * cookie Obtain * @param {String} key attribute */ export const cookieGet = (key) => { const cookieStr = unescape(document.cookie) const arr = cookieStr.split('; ') let cookieValue = '' for (var i = 0; i < arr.length; i++) { const temp = arr[i].split('=') if (temp[0] === key) { cookieValue = temp[1] break } } return cookieValue }
40.cookieRemove
cookie deletion
/** * cookie delete * @param {String} key attribute */ export const cookieRemove = (key) => { document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}` }
str
41.strTrimLeftOrRight
Remove left and right spaces
/** * Remove left and right spaces * @param {String} str character */ export const strTrimLeftOrRight = str => { return str.replace(/(^\s*)|(\s*$)/g, "") }
42.strInclude
Determine whether a character contains a value
/** * Determine whether a character contains a value * @param {String} str character * @param {String} value character */ export const strInclude = (str, value) => { return str.includes(value) }
43.strBeginWith
Determine whether a character begins with a certain character
/** * Determine whether a character begins with a certain character * @param {String} str character * @param {String} value character */ export const strBeginWith = (str, value) => { return str.indexOf(value) === 0 }
44.strReplace
Global replace one character with another
/** * Global replace one character with another * @param {String} str character * @param {String} valueOne Included characters * @param {String} valueTwo Characters to replace, optional */ export const strReplace = (str, valueOne, valueTwo) => { return str.replace(new RegExp(valueOne,'g'), valueTwo) }
45.strToCapital
Convert all letters to uppercase
/** * Convert all letters to uppercase * @param {String} str character */ export const strToCapital = (str) => { return str.toUpperCase() }
46.strToLowercase
Convert all letters to lowercase
/** * Convert all letters to lowercase * @param {String} str character */ export const strToLowercase = (str) => { return str.toLowerCase() }
47.strToCapitalLetter
Convert all letters to uppercase
/** * Convert all letters to uppercase * @param {String} str character */ export const strToCapitalLetter = (str) => { const strOne = str.toLowerCase() return strOne.charAt(0).toUpperCase() + strOne.slice(1) }
thrDeb
48.throttle
throttle
/** * throttle * @param {*} func Execution function * @param {*} delay Throttling time, MS */ export const throttle = function(func, delay) { let timer = null return function() { if (!timer) { timer = setTimeout(() => { func.apply(this, arguments) // Or direct func() timer = null }, delay) } } }
49.debounce
Anti shake
/** * Anti shake * @param {*} fn Execution function * @param {*} wait Anti shake time, MS */ export const debounce = function(fn, wait) { let timeout = null return function() { if (timeout !== null) clearTimeout(timeout)// Clear the last record delay if triggered multiple times timeout = setTimeout(() => { fn.apply(this, arguments) // Or direct fn() timeout = null }, wait) } }
time
50.getYear
Year of acquisition
/** * Year of acquisition */ export const getYear = () => { return new Date().getFullYear() }
51.getMonth
Get month
/** * Get current month * @param {Boolean} fillFlag Boolean value, fill 0 or not, default is true */ export const getMonth = (fillFlag=true) => { const mon = new Date().getMonth() + 1 const monRe = mon if (fillFlag) mon < 10 ? `0${mon}` : mon return monRe }
52.getDay
Acquisition date
/** * Acquisition date * @param {Boolean} fillFlag Boolean value, fill 0 or not */ export const getDay = (fillFlag=true) => { const day = new Date().getDate() const dayRe = day if (fillFlag) day < 10 ? `0${day}` : day return dayRe }
53.getWhatDay
What day is it
/** * Get the day of the week */ export const getWhatDay = () => { return new Date().getDay() ? new Date().getDay() : 7 }
54.getMonthNum
Get current month days
/** * Get current month days * @param {String} year Particular year * @param {String} month Month */ export const getMonthNum = (year, month) => { var d = new Date(year, month, 0) return d.getDate() }
55.getYyMmDdHhMmSs
Get the current time yyyy MM DD, HH: mm: SS
/** * Get the current time yyyy MM DD, HH: mm: SS */ export const getYyMmDdHhMmSs = () => { const date = new Date() const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hours = date.getHours() const minu = date.getMinutes() const second = date.getSeconds() const arr = [month, day, hours, minu, second] arr.forEach(item => { item < 10 ? '0' + item : item }) return ( year + '-' + arr[0] + '-' + arr[1] + ' ' + arr[2] + ':' + arr[3] + ':' + arr[4] ) }
56.timesToYyMmDd
Time stamp converted to MM DD YY
/** * Time stamp converted to MM DD YY * @param times time stamp * @param ymd Format type (yyyy MM DD, yyyy / mm / DD) * @param hms Optional, format type (hh,hh:mm,hh:mm:ss) * @returns {Year and month} */ export const timesToYyMmDd = (times, ymd, hms) => { const oDate = new Date(times) const oYear = oDate.getFullYear() const oMonth = oDate.getMonth() + 1 const oDay = oDate.getDate() const oHour = oDate.getHours() const oMin = oDate.getMinutes() const oSec = oDate.getSeconds() let oTime // Last splicing time // Format: switch (ymd) { case 'yyyy-mm-dd': oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay) break case 'yyyy/mm/dd': oTime = oYear + '/' + getzf(oMonth) + '/' + getzf(oDay) break } // Hour minute second format switch (hms) { case 'hh': oTime = ' '+oTime + getzf(oHour) break case 'hh:mm': oTime = oTime + getzf(oHour) + ':' + getzf(oMin) break case 'hh:mm:ss': oTime = oTime + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSec) break } return oTime }
57.YyMmDdToTimes
Convert mm / DD / yyyy to time stamp
/** * Convert mm / DD / yyyy to time stamp * @param {String} time yyyy/mm/dd Or yyyy MM DD or yyyy MM DD HH: mm or yyyy MM DD HH: mm: SS */ export const YyMmDdToTimes = (time) => { return new Date(time.replace(/-/g, '/')).getTime() }
58.compareTimeOneLessTwo
/** * Compare time 1 less than time 2 * @param {String} timeOne Time 1 * @param {String} timeTwo Time 2 */ export const compareTimeOneLessTwo = (timeOne, timeTwo) => { // Judge whether timeOne and timeTwo are return new Date(timeOne.replace(/-/g, '/')).getTime()<new Date(timeTwo.replace(/-/g, '/')).getTime() }
url
59.getQueryString
Get the parameters of the parameter after the url~~~~
/** * Get the parameters of the parameter after the url * @param {String} name */ export function getQueryString(name) { const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i') const url = window.location.href const search = url.substring(url.lastIndexOf('?') + 1) const r = search.match(reg) if (r != null) return unescape(r[2]) return null }
summary
Codeword is not easy, continuous update, welcome to start!
Recommend a bug management tool to you, please stamp
bug management tools