常用的JS装饰器函数记录 --- 缓存,防抖,节流 --- 持续更新···

1、缓存函数

实现功能

当第一次函数调用,保存该函数

第二次调用传相同参数时,直接输出缓存结果优化性能

let worker = {
  slow(min, max) {
    console.log(`Called with ${min},${max}`);
    return min + max;
  }
};

function cachingDecorator(func) {
  // 用map来保存缓存
  let cache = new Map(); 
  return function() {
    // 用hash来记录参数
    let key = hash(arguments); 
    if (cache.has(key)) {  //  如果有缓存该函数并且参数相同
      return cache.get(key); //  返回同样结果
    }

    // 记录第一次函数的结果
    let result = func.call(this, ...arguments); 

    // 保存下结果,与函数参数
    cache.set(key, result);
    // 返回第一次的结果
    return result;
  };
    function hash(args) {
      // 参数的拼接
      return [].join.call(args) // 3,5
    }
}


// 将函数用缓存包装
worker.slow = cachingDecorator(worker.slow);

console.log( worker.slow(3, 5) ); // works
console.log( "Again " + worker.slow(3, 5) ); // 从 (cached) 中获取的参数 第二次没用调用slow

2、防抖装饰器(debounce)

假设delay为1秒

在单位时间 (> 1)内 事件触发的间隔时间小于 1 秒的都不执行

function doubounce (func,delay){
    let timer = null
    return function(...args){
        if(timer)  clearTimeout(timer)
        timer = setTimeout(()=>{
            func.apply(this,args)
        },delay)
    }
}

// 用防抖装饰器包装后的函数再使用就有防抖作用
let xxx = doubounce(func,delay)
xxx('args')

3、节流装饰器(throttle)

在单位时间 (>1)内 不论事件触发多少次都只会在1秒后执行一次

function throttle(func,delay){
	let timer 
	return function(...args){
		if(!timer){
			timer = setTimeout(() => {
				timer = null
				func.apply(this,args)
			}, delay);
		}
	}
}

// 用节流装饰器包装后的函数再使用就有节流作用
let xxx = throttle(func,delay)
xxx('args')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值