common functions

This article will be updated from time to time, please take it away if you need it

1. Parsing URL parameters

Parsing URL parameters is a very common function in front-end development

const _getParams = (url) => {
    // 补全代码
    const params=url.split('?')[1].split('&')
    const obj={}
    params.forEach(item=>{
        obj[item.split('=')[0]]=item.split('=')[1]
    })
    return obj
}

2. Format time function

The backend returns the timestamp, and the frontend displays the year, month, day, hour, minute, and second


function formatDate (value) {
    if (typeof (value) == 'undefined') {
        return ''
    } else {
        let date = new Date(parseInt(value))
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? ('0' + MM) : MM
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        let h = date.getHours()
        h = h < 10 ? ('0' + h) : h
        let m = date.getMinutes()
        m = m < 10 ? ('0' + m) : m
        let s = date.getSeconds()
        s = s < 10 ? ('0' + s) : s
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
}

Reverse conversion, convert year, month, day, hour, minute and second to timestamp


function formatDate() {
    var date = new Date('2020-04-07 18:08:58');
    // 有三种方式获取
    var time1 = date.getTime();
    var time2 = date.valueOf();
    var time3 = Date.parse(date);
}

3. Anti-shake

// 函数防抖 (只执行最后一次点击)
const debounce = (fn: Function, delay = 300) => {
  let timer: NodeJS.Timeout | null;
  return function(...args: any) {
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
          timer = null;
          fn.apply(this, args);
      }, delay);
  };
};

Four, throttling

// 节流(n秒内只下执行一次)
const throttle = (fn: any, delay = 500) => {
  let flag = false;
  return function(...args: any) {
      if (!flag) {
          flag = true;
          setTimeout(() => {
              console.log(flag);

              flag = false;
              // @ts-ignore
              fn.apply(this, args);
          }, delay);
      }
  };
}

5. Keyword highlighting

When the user searches for a keyword in the input box, the keywords in the displayed association list will be changed in color, so that the user can see the desired result more intuitively.

export const lightFn = (str, targetStr) => {
    // 忽略大小写且全局匹配
  const reg = new RegExp(targetStr, "ig")
  return str.replace(reg, match => {
    return `<span style="color:red">${match}</span>`
  })
}

6. Data type detection

//检测变量的数据类型
export function getParamType(item) {
    if (item === null) return null;
    if (item === undefined) return undefined;
    return Object.prototype.toString.call(item).slice(8, -1);
}
//返回String, Function, Boolean, Object, Number

7. Function currying

    That is, a technology that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result

const curring = fn => {
 const { length } = fn
 const curried = (...args) => {
 return (args.length >= length
 ? fn(...args)
 : (...args2) => curried(...args.concat(args2)))
 }
 return curried
 }

X, the implementation of one line of code

One-line code implementation of commonly used JS methods

Guess you like

Origin blog.csdn.net/z1093541823/article/details/126605720