Worth collecting necessary tool functions for front-end development

Worth collecting necessary tool functions for front-end development

Preface

Take advantage of your spare time to sort out some tool-like functions that are often used in ordinary project development. Each is pro-tested and effective, ready to use out of the box.

1. Determine whether the current environment is a mobile phone


/**
 *  
 * 
 * @return {Boolean}   
 * 
 */
 export const isMobile=() =>{
     if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            return true
        } else {
            return false
      }
   }
   
 

2. Check whether the current environment is a WeChat environment


/**
 *  
 * 
 * @return {Boolean}   
 * 
 */
export const isWeixin =() =>{      
      const ua = navigator.userAgent.toLowerCase();
      if(ua.match(/MicroMessenger/i)==="micromessenger") {
           return true;
     } else {
            return false;
      }
  }
 

3. Check whether the browser is zoomed in

/**
 *  
 * 
 * @param {Boolean } rsize   , 
 * @return {Boolean | Number}   
 * 
 */
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
}
 

4. Get the url parameter of the common address

/**
 *  url 
 *  http://localhost:8080/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
 * 
 * @param {String} name 
 * @return {Boolean | String}   
 * 
 */
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; 
}
 

5. Get the hash mode address url parameter

/**
 *  hash url 
 *  http://localhost:8080/#/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
 * 
 * @param {String} name 
 * @return {Boolean | String}   
 * 
 */
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;
}
 

6. Timestamp conversion

/**
 *  
 * 
 * @param {Number} date  
 * @param {String} fmt    yyyy-MM-dd HH:mm:ss
 * @return {String} fmt    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;
};
 

7. Before the timestamp is converted to what

/**
 *  
 * 
 * @param {Number} times  
 * @return {String}  timeAgoLabel(1606273724459)  
 * 
 */
export const timeAgoLabel = times => {
  let nowTimes = new Date().getTime()
  let diff2.= (nowTimes - times)/1000
  let agoLabel = ''
  if (diff2.< 60) {
    agoLabel = ' '
  } else if (diff2.< 60 * 60) {
    agoLabel = Math.floor(diffSecond/60) + ' '
  } else if (diff2.< 60 * 60 * 24) {
    agoLabel = Math.floor(diffSecond/3600) + ' '
  } else if (diff2.< 60 * 60 * 24 * 30) {
    agoLabel = Math.floor(diffSecond/(3600 * 24)) + ' '
  } else if (diff2.< 3600 * 24 * 30 * 12) {
    agoLabel = Math.floor(diffSecond/(3600 * 24 * 30)) + ' '
  } else {
    agoLabel = Math.floor(diffSecond/(3600 * 24 * 30 * 12)) + ' '
  }
  return agoLabel
}
 

8. Generate random numbers (numbers) of arbitrary digits

/**
 *  ( )
 * 
 * @param {Number} n  
 * @return {Number}  
 * 
 */
export const randomNumber =n =>{
      let rnd = '';
      for (let i = 0; i < n; i++) {
        rnd += Math.floor(Math.random() * 10);
      }
      return rnd;
}
 

9. Randomly generate a custom-length, unique combination of letters and numbers, which can be used for id identification

/**
 *  id 
 * 
 * @param {Number} randomLength  10
 * @return {String}  
 * 
 */
export const randomId =(randomLength = 10) =>{
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
},
 

10.js array deduplication (in the case of complex data with ID)

 /**
  * js ( ID )
  *  (hash)
  * 
  * @param {Array} repeatArray  
  * @return {Array}  
  * 
  */
 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 ( ID )
  *  (hash + reduce)
  * 
  * @param {Array} repeatArray  
  * @return {Array}  
  * 
  */
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		   
	
	}, []);
}
 

11.Shallow copy

/**
 *  
 * 
 * @param {Array | Object} objOrArr  
 * @return {Array | Object}  
 * 
 */
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
}
 

12.Deep copy

/**
 *  
 * 
 * @param {Array | Object} objOrArr  
 * @return {Array | Object}  
 * 
 */
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
}
 

13. Ajax function encapsulated by promise

/**
 * promise ajax 
 * 
 * @param {String} method  
 * @param {String} url  
 * @param {Object} params  
 * 
 */
export const ajax=(method,url, params) =>{		
    //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);

            }			

    })

}
 

14.js floating-point number calculation addition, subtraction, multiplication and division precision loss solution

/**
 * js 
 * 
 * @param {Number} a  a
 * @param {Number} b  b
 * @param {String} computeType   add   subtract   multiply   divide 
 * @return {Number}  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) { // 
                    result = n1 + n2
                } else if (t1 > t2) { //o1     o2
                    result = n1 + n2 * (t1/t2)
                } else { //o1     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)
}
 

15. Debounce

/**
 *   (debounce) 
 * 
 * @param {Function} fn  
 * @param {Number} wait   
 * @param {Boolean} immediate  true debounce wait 
 * @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)
    }
}
 

16. Throttle

/**
 *  (throttle)  100~500 ms 
 * 
 * @param {Function} fn  
 * @param {Number} wait   
 * @param {Boolean} immediate  true debounce wait 
 * @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)
        }
    }
}
 

17. Convert file size into units

/** 
 *  
 * 
 * @param {Number} bytes  
 * @param {String} units  metric
 * @param {Number} precision  1
 * @return {String}  byteSize(1580) 1.6 kB
 * 
*/
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()  
}
 

18. Copy a string to the clipboard

/**
 *  
 * @param {String} str  
 * @return {String}   copyToClipboard(' ')
 * 
 */
 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);
      }
}
 

19. Scroll smoothly to the top of the page

/**
 *  
 * 
 */
export const scrollToTop = () => {  
    const c = document.documentElement.scrollTop || document.body.scrollTop;  
    if (c > 0) {  
    window.requestAnimationFrame(scrollToTop);  
    window.scrollTo(0, c - c/8);  
    }  
}

 

Thanks for reading, please pay attention to more content: