Summary of JavaScript Common Tools Function Library

  • 2021-08-16 23:03:35
  • OfStack

A deep copy of an object or array


/**
 *  A deep copy of an object or array 
 * @param {*} cloneObj  Cloned object 
 * @param {*} targetObj  Cloned target object 
 * @param {*} isOverride  If the attributes are duplicate, whether to overwrite the attributes of the cloned object 
 */
function deepClone(cloneObj, targetObj, isOverride = true) {
 const _toString = Object.prototype.toString
 if (_toString.call(cloneObj) !== '[object Array]' && _toString.call(cloneObj) !== '[object Object]') {
  return cloneObj
 }
 var cloneTarget = _toString.call(cloneObj) === '[object Array]' ? [] : {}
 for (let key in cloneObj) {
  if (Object.prototype.hasOwnProperty.call(cloneObj, key)) {
   if (_toString.call(cloneObj[key]) === '[object Array]' || _toString.call(cloneObj[key]) === '[object Object]') {
    cloneTarget[key] = deepClone(cloneObj[key])
   } else {
    cloneTarget[key] = cloneObj[key]
   }
  }
 }
 if (targetObj && (_toString.call(cloneObj) === _toString.call(targetObj))) {
  // Note here that the target object of cloning should also be deepClone Under 
  cloneTarget = isOverride
   ? Object.assign(cloneTarget, deepClone(targetObj))
   : Object.assign(deepClone(targetObj), cloneTarget)
 }
 return cloneTarget
}

Accurately judge the data type


// Accurately judge the data type 
function getVerifyDataTypes() {
 const types = ["String", "Number", "Boolean", "Null", "Undefined", "Function", "Object", "Array", "Date", "Error", "RegExp", "Symbol", "Map", "Set"]
 let Type = {}
 //  Example usage: Type.isString('javascript')
 for (let i = 0; i < types.length; i++) {
  Type[`is${types[i]}`] = obj => Object.prototype.toString.call(obj) === `[object ${types[i]}]`
 }
 //  Determine whether the string is json Format 
 Type.isJsonStr = str => {
  if (typeof str == 'string') {
   try {
    let obj = JSON.parse(str);
    if (obj && typeof obj == 'object') {
     return true;
    }
    return false;
   } catch (e) {
    return false;
   }
  } else {
   return false;
  }
 }
 return Type
}

Date formatting


/**
 *  Date formatting 
 * @param {*} date  Date object 
 * @param {*} beforeHyphen  Year, month and day hyphen 
 * @param {*} afterHyphen  Time division second hyphen 
 */
function formatDate(date = new Date(), beforeHyphen = '-', afterHyphen = ':') {
 const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
 }
 const year = date.getFullYear()
 const month = date.getMonth() + 1
 const day = date.getDate()
 const hour = date.getHours()
 const minute = date.getMinutes()
 const second = date.getSeconds()
 const ymd = [year, month, day].map(formatNumber).join(beforeHyphen)
 const hms = [hour, minute, second].map(formatNumber).join(afterHyphen)
 return `${ymd} ${hms}`
}

Convert the timestamp to the remaining days, hours, minutes and seconds


/**
 *  Converts the timestamp to the remaining days, hours, minutes, seconds, 1 It is generally applied to countdown scenes 
 * @param {*} timestamp  Time stamp 
 */
function converTimestamp(timestamp) {
 const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
 }
 let day = Math.floor((timestamp / 1000 / 3600) / 24);
 let hour = Math.floor((timestamp / 1000 / 3600) % 24);
 let minute = Math.floor((timestamp / 1000 / 60) % 60);
 let second = Math.floor(timestamp / 1000 % 60);
 return {
  day: day,
  hour: formatNumber(hour),
  minute: formatNumber(minute),
  second: formatNumber(second)
 }
}

Randomly fetch 1 item from the array


//  Randomly fetch from the array 1 Items 
function getRandomItemByArray(items) {
 return items[Math.floor(Math.random() * items.length)];
}

Convert an array with a parent-child relationship into tree-structured data


let data = [
 { parentId: 0, id: 1, value: 'xxx' },
 { parentId: 1, id: 3, value: 'xxx' },
 { parentId: 4, id: 6, value: 'xxx' },
 { parentId: 3, id: 5, value: 'xxx' },
 { parentId: 2, id: 4, value: 'xxx' },
 { parentId: 1, id: 2, value: 'xxx' },
]

//  Convert to tree Array Structure 
function toTreeAry(arr, pId = 0) {
 return arr
  .filter(({ parentId }) => parentId === pId)
  .map(a => ({
   ...a,
   children: toTreeAry(arr.filter(({ parentId }) => parentId !== pId), a.id)
  }))
}

//  Convert to tree Object Structure 
function toTreeObj(arr, pId = 0) {
 let res = {}
 arr.filter(({ parentId }) => parentId === pId)
  .forEach(a => {
   res[a.id] = {
    ...a,
    children: toTreeObj(arr.filter(({ parentId }) => parentId !== pId), a.id)
   }
  })
 return res
}

console.log(toTreeAry(data))
console.log(toTreeObj(data))

Generate random strings


//  Random string 
const randomStr = () => {
 return new Date().getTime() + '-' + Math.random().toString(36).substr(2)
}

Filter html tags


//  Filter html Label 
const filterHTMLTag = (str) => {
 str = str.replace(/<\/?[^>]*>/g, ''); // Removal HTML Tag
 str = str.replace(/[|]*\n/, '') // Remove the space at the end of the line 
 str = str.replace(/&npsp;/ig, ''); // Remove npsp
 return str;
}

The above is the JavaScript commonly used tool library summary details, more about JavaScript tool library information please pay attention to other related articles on this site!


Related articles: