写一个LRU缓存函数

LRU就是最近最少访问

参考Map()

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
var LRUCache = function(capacity) {
this.capacity = capacity; //capacity为缓存容量
this.map = new Map();
};

LRUCache.prototype.get = function(key) {
let val = this.map.get(key);
if(val === undefined) {
return -1
}
this.map.delete(key);
this.map.set(key, val);
return val
};

LRUCache.prototype.put = function(key, value) {
if(this.map.has(key)){
this.map.delete(key)
}
this.map.set(key, value);
if(this.map.size > this.capacity){
let iterator1 = this.map.keys();
this.map.delete(iterator1.next().value);
}
};

写个防抖和节流函数

链接

  1. 防抖(debounce)函数

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

    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
    // 自己遇到过的场景:公装云首页8秒弹窗,切换tab重新计时;

    function modal(params) {
    let times;
    if(times){
    clearTimeout(times)
    }
    times = setTimeout(function () {
    showModal() // 显示具体弹框函数
    }, 8000)
    }

    // 其他写法
    function debounce(func, wait) {
    let timeout;
    return function () {
    let context = this;
    let args = arguments; // arguments对象是func 传入的参数

    if (timeout) clearTimeout(timeout);

    timeout = setTimeout(() => {
    func.apply(context, args)
    }, wait);
    }
    }
    debounce(count,1000); // 调用
  2. 节流(throttle)函数

    规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

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
// 定时器加锁版
function throttle(fn, delay) {
let flag = true,
timer = null
return function(...args) {
let context = this
if(!flag) return

flag = false
clearTimeout(timer)
timer = setTimeout(function() {
fn.apply(context,args)
flag = true
},delay)
}
}

//时间戳版
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}

/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
* @param type 1 表时间戳版,2 表定时器版
*/
function throttle(func, wait ,type) {
if(type===1){
let previous = 0;
}else if(type===2){
let timeout;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();

if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}

区别

他们都是可以防止一个函数被无意义的高频率调用,区别在于:

函数节流:是确保函数特定的时间内至多执行一次。 函数防抖:是函数在特定的时间内不被再调用后执行。