常用工具函数

# 常用工具函数封装

封装一些常用的工具方法

# debounce

防抖: 事件被触发n秒后再执行回调, 如果在这n秒内又被触发, 则重新开始计时

点击查看代码
/**
 * 防抖
 * @param {*} fn 
 * @param {*} ms 
 * @returns 
 */
function debounce(fn, ms = 0) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), ms)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# throttle

节流: 在一定时间内仅触发一次函数, 如果在这段时间内被多次触发, 只一次生效

点击查看代码
/**
 * 节流函数
 * @param {function} fn 回调函数
 * @param {number} ms 等待时间
 * @returns 
 */
function throttle(fn, ms) {
  let inThrottle, lastFn, lastTime
  return function(...args) {
    const context = this
    if (!inThrottle) {
      fn.apply(context, args)
      lastTime = Date.now()
      inThrottle = true
    } else {
      clearTimeout(lastFn)
      lastFn = setTimeout(function() {
        // 当前时间 - 上一次触发的时间 大于 等待时间
        if (Date.now() - lastTime >= ms) {
          fn.apply(context, args)
          lastTime = Date.now()
        }
      }, Math.max(ms - (Date.now() - lastTime), 0))
    }
  }

  // 时间戳
  // let previous = 0;
  // return function (...args) {
  //   const now = +new Date();
  //   if (now - previous > wait) {
  //     func.apply(this, args);
  //     previous = now;
  //   }
  // };

  // 定时器
  // let timer = null;
  // return function (...args) {
  //   if (!timer) {
  //     timer = setTimeout(() => {
  //       func.apply(this, args);
  //       timer = null;
  //     }, wait);
  //   }
  // };

  // 时间戳+定时器
  // let previous = 0,
  //   timer = null
  
  // return function(...args) {
  //   const now = +new Date()
  //   const remaining = ms - (now - previous)
  //   if (remaining <= 0) {
  //     clearTimeout(timer)
  //     timer = null
  //     previous = now
  //     fn.apply(this, args)
  //   } else if (!timer){
  //     timer = setTimeout(() => {
  //       timer = null
  //       previous = +new Date()
  //       fn.apply(this, args)
  //     }, remaining)
  //   }
  // }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

# 生成随机字符串

refs: nanoid - urlAlphabet (opens new window)

随机生成一段字符串

点击查看代码
const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'

function randomStr(size = 16, dict = urlAlphabet) {
  let id = '', i = size
  const len = dict.length

  while (i--) {
    id += dict[(Math.random() * len) | 0]
  }

  return id
}
1
2
3
4
5
6
7
8
9
10
11
12

# 简单字符串模板引擎

简易字符串模板引擎

点击查看代码
/**
 * Dead simple template engine, just like Python's `.format()`
 * @param {string} str 
 * @param  {...any[]} args 
 * @returns string
 * 
 * @example
 * ```
 * template(
 *  'Hello {0}! My name is {1}.',
 *  'World',
 *  'Zeke'
 * )
 * // Hello World! My name is Zeke.
 * ```
 */
function template(str, ...args) {
  return str.replace(/{(\d+)}/g, (match, key) => {
    const index = Number(key)
    if (Number.isNaN(index)) {
      return match
    }

    return args[index]
  })
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 参考资料