前端面试常见题型——节流防抖函数柯里化

  <style>
    #box {
      width: 0;
      height: 0;
      border: 40px solid transparent;
      border-bottom: 40px solid tomato;
    }
  </style>
<body>
<!-- css实现三角形 -->
<div id="box"></div>

<!-- 实现节流防抖 -->
<button id="ok">ok</button>
<script>
 
 /* 节流 */
function throttle(func,wait){
  let previous = 0 ;
  return function () {
    let args = arguments;
    let now = Date.now();
    if((now-previous) > wait) {
      func.apply(this,args)
    }
    previous = now;
  }  
}

 /* 防抖 */
 function debounce(func,delay){
  let timer;
  return function(){
    let args = arguments;
    if(timer) clearTimeout(timer);
    timer = setTimeout(function (){
      func.apply(this,args)
    },delay)
  }
}
  function showClick(str = 'click') { console.log(str) }
  document.getElementById('ok').addEventListener('click',
    function () {
      throttle(showClick,1000)('throttle')
    }
  )
  document.getElementById('ok').addEventListener('click',
    function() {
      debounce(showClick,1000)('debounce')
    }
  )

/*  函数柯里化 */
// 普通函数
function normalAdd(a,b){
  return a + b
} 
// 柯里化函数
function curryingAdd (x) {
  return function (y) {
    return x+y
  }
}

// 经典面试题
function add() {
    // 第一次执行时,定义一个数组专门用来存储所有的参数
    var _args = Array.prototype.slice.call(arguments);
    // 在内部声明一个函数,利用闭包的特性保存_args并收集所有的参数值
    var _adder = function() {
        _args.push(...arguments);
        return _adder;
    };
    // 利用toString隐式转换的特性,当最后执行时隐式转换,并计算最终的值返回
    _adder.toString = function () {
        return _args.reduce(function (a, b) {
            return a + b;
        });
    }
    return _adder;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值