pre-me-hooks

简单易用的hooks,目前支持通用的debounce,throttle以及curry.


License
ISC
Install
npm install pre-me-hooks@1.0.2

Documentation

pre-me-hooks

简单易用的hooks,目前支持通用的debounce,throttle以及curry.

详细介绍

  1. useDebounce
/**
 * 防抖函数
 * @param {Function} fn 被防抖函数
 * @param {number} wait 等待时长
 * @param {boolean} immediate 是否立即执行
 */
const debounce = (fn , wait, immediate) => {
  let timer = null;
  return () => {
    if(immediate) {
      fn(...arguments)
    }
    if (timer) {
      clearInterval(timer)
    }
    timer = setTimeout(() => {
      fn(...arguments)
    }, wait)
  }
};
  1. useThrottle
/**
 * 节流函数
 * @param {Function} fn 节流的函数
 * @param {number} wait 等待时长
 */
const throttle = (fn, wait) => {
  let prev= new Date();
  return () => {
    const now = new Date();
    if (now - prev > wait) {
      fn(...arguments);
      prev = now;
    }
  }
}
  1. useCurry
/**
 * 柯里化函数
 * @param {Function} fn 需要被执行柯里化的函数
 * @returns {Function} curryFunc 如果参数以符合预期参数,执行函数并返回结果;如果参数值仍有缺省,则可继续传入参数
 */
const curry = (fn) =>
  curryFunc = (...args) =>
    args.length < fn.length ? (...arg) => curryFunc(...args, ...arg) : fn(...args);