lodash-chain

lodash-chain

by 郭 凡

HTML

<div id="debounce"></div>
<br>
<div id="throttle"></div>
<script src="//cdn.bootcss.com/lodash.js/4.6.1/lodash.js"></script>

CSS

#debounce {
  width:100px;
  height:100px;
  border: 1px solid #f00;
}
#throttle {
   width:100px;
  height:100px;
  border: 1px solid #00f;
}

JavaScript

//参考http://blog.csdn.net/Soaring_Tiger/article/details/48136871
//Chain-进行复杂的多步操作
//Chain的调用方式有两种:一种是显式调用(Explicit Chaining),一种是隐式调用(Implicit Chaining)
//显式调用,__chain__: true,实现延迟计算,即:求值操作等到 _value()被调用时再执行
let numbers = [1, 2, 3, 4, 5];
let sumOfEvenSquares = _.chain(numbers) //注意numbers放置的位置
    .filter(n => n % 2 === 0)
    .map(n => n * n)
    .sum()
    .value();    
console.log(sumOfEvenSquares);

//隐式调用,__chain__: false
let _sumOfEvenSquares = _(numbers) //注意numbers的位置,不需要显式的使用chain关键字
    .filter(n => n % 2 === 0)
    .map(n => n * n)
    .sum();
console.log(_sumOfEvenSquares);

console.log(_.chain(numbers));//__chain__: true
console.log(_(numbers));//__chain__: false

function log() {
	console.log(new Date().getTime());
}
//debounce 空闲时间的间隔控制,是空闲时间必须大于或等于 一定值的时候,才会执行调用方法,主要用于文本输入keydown 事件,keyup 事件
 document.getElementById('debounce').onclick = _.debounce(log, 2000);
 //throttle 函数节流,就是函数调用的频度控制器,连续执行时间间隔控制,主要应用mousemove,DOM 元素动态定位,window对象的resize和scroll 事件
 document.getElementById('throttle').onclick = _.throttle(log, 2000);
 
 //生成uuid
 let uuid = (function() {
        var unique = 0;
        return function() {
            unique++;
            return '(key.' + unique + ')';
        }
    })();
    console.log(uuid());
    console.log(uuid());