preface

Take the time to sort out some of the utility class functions that are often used in normal project development. Each is beta effective, right out of the box.

1. Check whether the current environment is mobile


/** * Check whether the current environment is mobile **@return {Boolean}  Returns the result * */
 export const isMobile=() = >{
     if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            return true
        } else {
            return false}}Copy the code

2. Determine whether the current environment is wechat environment


/** * Indicates whether the current environment is wechat **@return {Boolean}  Returns the result * */
export const isWeixin =() = >{      
      const ua = navigator.userAgent.toLowerCase();
      if(ua.match(/MicroMessenger/i) = = ="micromessenger") {
           return true;
     } else {
            return false; }}Copy the code

3. Check whether the browser zooms in

/** * Check whether the browser zooms in **@param {Boolean } Rsize Specifies whether to return an enlarged value. The default value is no *@return {Boolean | Number}  Returns the result * */
export const detectZoom=rsize= >{
  let ratio = 0
  const screen = window.screen
  const ua = navigator.userAgent.toLowerCase()

  if (window.devicePixelRatio) {
    ratio = window.devicePixelRatio
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) ratio = screen.deviceXDPI / screen.logicalXDPI
  } else if (window.outerWidth&& window.innerWidth) {
    ratio = window.outerWidth / window.innerWidth
  }

  if (ratio) ratio = Math.round(ratio * 100)

  return rsize ? ratio : ratio === 100
}
Copy the code

4. Obtain the URL parameters of the common address

/** * Obtain common url parameters * for example, http://localhost:8080/? token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864 * *@param {String} name 
 * @return {Boolean | String} Returns the value * */
export const getUrlParam = name= >{
  const reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"); 
  const r = window.location.search.substr(1).match(reg);  
  if(r ! =null) return decodeURI(r[2]); return false; 
}
Copy the code

5. Obtain hash mode URL parameters

/** * Obtain hash address URL parameters * for example, http://localhost:8080/#/? token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864 * *@param {String} name 
 * @return {Boolean | String} Returns the value * */
export const getUrlHashParam =name= >{
  const w = window.location.hash.indexOf("?");
  const query = window.location.hash.substring(w + 1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=");
    if (pair[0] == name) {
      return pair[1]; }}return false;
}
Copy the code

6. Timestamp conversion

/** * timestamp conversion **@param {Number} Date Timestamp *@param {String} FMT Time format, for example, YYYY-MM-DD HH: MM: SS *@return {String} FMT returns the converted time, formatDate(value, "YYYY-MM-DD hh: MM: ss") * */
export const formatDate = (date, fmt) = > {
  date = new Date(date);
  if (isNaN(date.getDate())) return date;
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1."d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(` (${k}) `).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp. $1,RegExp.$1.length === 1 ? str : ("00"+ str).substr(str.length) ); }}return fmt;
};
Copy the code

7. Before the timestamp is converted to what

/** * what is the timestamp converted to before **@param {Number} Times Indicates the timestamp *@return {String} Return result, timeAgoLabel(1606273724459) output: just * */
export const timeAgoLabel = times= > {
  let nowTimes = new Date().getTime()
  let diffSecond = (nowTimes - times) / 1000
  let agoLabel = ' '
  if (diffSecond < 60) {
    agoLabel = 'just'
  } else if (diffSecond < 60 * 60) {
    agoLabel = Math.floor(diffSecond / 60) + 'Minutes ago'
  } else if (diffSecond < 60 * 60 * 24) {
    agoLabel = Math.floor(diffSecond / 3600) + 'Hours ago'
  } else if (diffSecond < 60 * 60 * 24 * 30) {
    agoLabel = Math.floor(diffSecond / (3600 * 24)) + 'days ago'
  } else if (diffSecond < 3600 * 24 * 30 * 12) {
    agoLabel = Math.floor(diffSecond / (3600 * 24 * 30)) + 'months'
  } else {
    agoLabel = Math.floor(diffSecond / (3600 * 24 * 30 * 12)) + 'years ago'
  }
  return agoLabel
}
Copy the code

8. Generate random number of arbitrary digits (number)

/** * Generates an arbitrary number of random digits **@param {Number} N Optional number of digits *@return {Number} Returns a random value * */
export const randomNumber =n= >{
      let rnd = ' ';
      for (let i = 0; i < n; i++) {
        rnd += Math.floor(Math.random() * 10);
      }
      return rnd;
}
Copy the code

9. Randomly generate a custom length and unique alphanumeric combination for id identification

/** * Randomly generates a user-defined length of letters and digits, which can be used as id identifier **@param {Number} RandomLength Specifies the number of bits of optional length. Default is 10 *@return {String} Returns a random value * */
export const randomId =(randomLength = 10) = >{
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)},Copy the code

10. Js array deduplicating (complex data with ID)

 /** * js array decrement (if complex data has ID) * method one (hash) **@param {Array} RepeatArray Array containing duplicate data *@return {Array} Return the data * */
 export const noRepeatArrayHash= repeatArray= >{
      const hash = {};
      const temp = [];
      for (let i = 0; i < repeatArray.length; i++) {
          if(! hash[repeatArray[i].id]) { hash[repeatArray[i].id] =true; temp.push(repeatArray[i]); }}return temp;
}

 /** * js array deduplicating (if complex data has ids) ** Hash + reduce **@param {Array} RepeatArray Array containing duplicate data *@return {Array} Return the data * */
export const noRepeatArrayReduce= repeatArray= >{
    const hash = {};
	return repeatArray.reduce(function(accumulator, currentValue){
	       if(! hash[currentValue.id]){ hash[currentValue.id]=true;
			   accumulator.push(currentValue)
           }  
           
        return accumulator		   
	
	}, []);
}
Copy the code

11. A shallow copy

/** * shallow copy **@param {Array | Object} ObjOrArr Specifies the object or array to copy@return {Array | Object} Return the copy result * */
export const shallowCopy = objOrArr= >{
    const type = objOrArr instanceof Array ? 'array' : 'object'
    let newObjOrArr = objOrArr instanceof Array ? [] : {}
    if(type === 'array'){
        newObjOrArr=[].concat(objOrArr)
    }else{
        for(let key in objOrArr){
            if(objOrArr.hasOwnProperty(key)){
                newObjOrArr[key]= objOrArr[key]
            }
        }
    }

    return newObjOrArr
}
Copy the code

12. A deep copy

/** * deep copy **@param {Array | Object} ObjOrArr Specifies the object or array to copy@return {Array | Object} Return the copy result * */
export const deepCopy= objOrArr= > {
    const type = objOrArr instanceof Array ? 'array' : 'object'
    let newObjOrArr = objOrArr instanceof Array ? [] : {}
    if (type === 'array') {
        newObjOrArr = JSON.parse(JSON.stringify(objOrArr))
    } else {
        for (let key in objOrArr) {
            if (objOrArr.hasOwnProperty(key)) {
                newObjOrArr[key] = typeof objOrArr[key] === 'object' ? deepCopy(objOrArr[key]) : objOrArr[key]
            }
        }
    }

    return newObjOrArr
}
Copy the code

13. Ajax functions wrapped in promise mode

/** * Ajax functions wrapped in promise mode **@param {String} Method Request method *@param {String} Url Request address *@param {Object} Params request parameter * */
export const ajax=(method,url, params) = >{		
    / / compatible with IE
    const request= window.XMLHttpRequest ? 	new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")	
    return new Promise(function(resolve,reject){
            request.onreadystatechange=function(){
                    if(request.readyState===4) {if(request.status===200){
                                resolve(JSON.parse(request.response));
                            }else{ reject(request.status); }}};if(method.toUpperCase() === "GET") {const arr = [];
                for(let key in params){
                    arr.push(key + '=' + params[key]);
                }
                const getData=arr.join("&");					
                request.open("GET",url +"?"+getData,true);
                request.send(null);
            }else if(method.toUpperCase() === "POST"){
                request.open("POST",url,true);
                request.responseType="json";
                request.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded; charset=utf-8'); request.send(params); }})}Copy the code

14. Js floating point number calculation of addition, subtraction, multiplication and division precision loss solution

/** * js floating point number calculation of addition, subtraction, multiplication and division precision loss solution **@param {Number} A The value is a *@param {Number} B The value is B *@param {String} ComputeType Add, subtract, multiply, and divide type Add Add Subtract subtract multiply divide *@return {Number} Return the result, floatNumber(0.11, 0.03, 'add') * */
export const floatNumber = (a, b, computeType) = >{
    const isInteger= obj= >{
        return Math.floor(obj) === obj
    }
    const toInteger= floatNum= >{
        const ret = {times: 1.num: 0}
        if (isInteger(floatNum)) {
            ret.num = floatNum
            return ret
        }
        const strfi  = floatNum + ' '
        const dotPos = strfi.indexOf('. ')
        const len    = strfi.substr(dotPos+1).length
        const times  = Math.pow(10, len)
        const intNum = parseInt(floatNum * times + 0.5.10)
        ret.times  = times
        ret.num    = intNum
        return ret
    }
    const operation=(a, b, computeType) = >{
        const o1 = toInteger(a)
        const o2 = toInteger(b)
        const n1 = o1.num
        const n2 = o2.num
        const t1 = o1.times
        const t2 = o2.times
        const max = t1 > t2 ? t1 : t2
        let result = null
        switch (computeType) {
            case 'add':
                if (t1 === t2) { // The two decimal places are the same
                    result = n1 + n2
                } else if (t1 > t2) { // O1 is greater than O2
                    result = n1 + n2 * (t1 / t2)
                } else { // O1 is less than O2
                    result = n1 * (t2 / t1) + n2
                }
                return result / max
            case 'subtract':
                if (t1 === t2) {
                    result = n1 - n2
                } else if (t1 > t2) {
                    result = n1 - n2 * (t1 / t2)
                } else {
                    result = n1 * (t2 / t1) - n2
                }
                return result / max
            case 'multiply':
                result = (n1 * n2) / (t1 * t2)
                return result
            case 'divide':
                result = (n1 / n2) * (t2 / t1)
                return result
        }

    }

    return operation(a, b, computeType)
}
Copy the code

15. Image stabilization (debounce)

/** * Debounce optimizes multiple high-frequency operations to perform ** only on the last time@param {Function} Fn requires an anti-shake function *@param {Number} Number of milliseconds to wait *@param {Boolean} Immediate Optional, set to true, debounce will call this function * at the start of the wait interval@return {Function}* * /
export const debounce= (fn, wait, immediate) = >{
    let timer = null

    return function() {
        let args = arguments
        let context = this

        if(immediate && ! timer) { fn.apply(context, args) }if (timer) clearTimeout(timer)
        timer = setTimeout(() = > {
            fn.apply(context, args)
        }, wait)
    }
}
Copy the code

16. The throttle (throttle)

/** throttle optimizes high-frequency operations to low-frequency operations every 100 to 500 ms@param {Function} Fn requires an anti-shake function *@param {Number} Number of milliseconds to wait *@param {Boolean} Immediate Optional executes immediately. If this is set to true, debounce will call this function * at the start of the wait interval@return {Function}* * /
export const throttle =(fn, wait, immediate) = >{
    let timer = null
    let callNow = immediate
    
    return function() {
        let context = this,
            args = arguments

        if (callNow) {
            fn.apply(context, args)
            callNow = false
        }

        if(! timer) { timer =setTimeout(() = > {
                fn.apply(context, args)
                timer = null
            }, wait)
        }
    }
}
Copy the code

17. The file size is converted into units

/** * The file size is converted into units **@param {Number} Size bytes *@param {String} Units Optional unit, default metric *@param {Number} Precision Specifies the number of digits. The precision of the value retains several decimal points. The default value is 1 *@return {String} Return with unit value, byteSize(1580), output 1.6KB * */
export const byteSize = (bytes, units='metric', precision=1) = > {
    let value=' ',
        unit=' '
    const base = units === 'metric' || units === 'metric_octet' ? 1000 : 1024
    const table = [
        { expFrom: 0.expTo: 1.metric: 'B'.iec: 'B'.metric_octet: 'o'.iec_octet: 'o' },
        { expFrom: 1.expTo: 2.metric: 'kB'.iec: 'KiB'.metric_octet: 'ko'.iec_octet: 'Kio' },
        { expFrom: 2.expTo: 3.metric: 'MB'.iec: 'MiB'.metric_octet: 'Mo'.iec_octet: 'Mio' },
        { expFrom: 3.expTo: 4.metric: 'GB'.iec: 'GiB'.metric_octet: 'Go'.iec_octet: 'Gio' },
        { expFrom: 4.expTo: 5.metric: 'TB'.iec: 'TiB'.metric_octet: 'To'.iec_octet: 'Tio' },
        { expFrom: 5.expTo: 6.metric: 'PB'.iec: 'PiB'.metric_octet: 'Po'.iec_octet: 'Pio' },
        { expFrom: 6.expTo: 7.metric: 'EB'.iec: 'EiB'.metric_octet: 'Eo'.iec_octet: 'Eio' },
        { expFrom: 7.expTo: 8.metric: 'ZB'.iec: 'ZiB'.metric_octet: 'Zo'.iec_octet: 'Zio' },
        { expFrom: 8.expTo: 9.metric: 'YB'.iec: 'YiB'.metric_octet: 'Yo'.iec_octet: 'Yio'}]for (let i = 0; i < table.length; i++) {
        const lower = Math.pow(base, table[i].expFrom)
        const upper = Math.pow(base, table[i].expTo)
        if (bytes >= lower && bytes < upper) {
            const retUnit = table[i][units]
            if (i === 0) {
                value = String(bytes)
                unit = retUnit
                break;
            } else {
                value = (bytes / lower).toFixed(precision)
                unit = retUnit
                break; }}}return `${value} ${unit}`.trim()  
}
Copy the code

Copy a string to the clipboard

/** * copies a string to the clipboard *@param {String} STR copied content *@return {String} Paste directly, copyToClipboard(' copy a string to clipboard ') * */
 export const copyToClipboard = str= > {
      const el = document.createElement('textarea');
      el.value = str;
      el.setAttribute('readonly'.' ');
      el.style.position = 'absolute';
      el.style.left = '-9999px';
      document.body.appendChild(el);
      const selected =document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      if (selected) {
          document.getSelection().removeAllRanges();
          document.getSelection().addRange(selected); }}Copy the code

Scroll smoothly to the top of the page

/** * smooth scroll to top of page ** /
export const scrollToTop = () = > {  
    const c = document.documentElement.scrollTop || document.body.scrollTop;  
    if (c > 0) {  
    window.requestAnimationFrame(scrollToTop);  
    window.scrollTo(0, c - c / 8); }}Copy the code

Thanks for reading, and stay tuned for more:

  • Github: Github Technology blog
  • Juejin: Juejin Technology Blog
  • CSDN: CSDN Technology Blog