白板代码

176 阅读1分钟

cacheRequest

const axios = require("axios");

const URL = "http://localhost:3001";

var cacheRequest = (function cacheRequest() {
  var memo = new Map();
  return function (url, callback) {
    if (!memo.has(url)) {
      const cb = axios.get(url);
      memo.set(url, cb);
      cb.then(callback);
    } else {
      memo.get(url).then(callback);
    }
  };
})();

cacheRequest(URL, function ({ data }) {
  console.log("1: ", data);
});

cacheRequest(URL, function ({ data }) {
  console.log("2: ", data);
});

限制并发请求

const axios = require("axios");

const URL = "http://localhost:3001";

const queue = Array.from({ length: 20 }).map((d, i) => {
  return () => axios.get(URL).then(({ data }) => console.log(i, data));
});

class Progress {
  constructor(queue, limit) {
    this.queue = queue;
    this.limit = limit;
    this.initRun();
  }

  initRun() {
    let index = 0;
    while (index < this.limit) {
      index++;
      this.nextRun();
    }
  }

  nextRun() {
    if (!this.queue.length) return;
    const rq = this.queue.shift();
    rq().finally(() => this.nextRun());
  }
}

new Progress(queue, 5);

debounce

debounce 装饰器版本

function debounce(delay) {
  return (target, option, descriper) => {
    const fn = descriper.value;
    descriper.value = (...rest) => {
      let timer = null;
      return () => {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => fn(...rest), delay);
      };
    };
    return descriper;
  };
}

class A {
  @debounce(3000)
  say(message) {
    console.log(message);
  }
}

const a = new A();

const fn = a.say("mu!");
fn();
fn();
fn();

debounce_leading 版本

function debounce_leading(fn, timeout = 300){
    let timer = null;
    return (...args)=>{
        if(!timer){ fn(...args) }
        clearTimeout(timer)
        timer = setTimeout(() => {
            timer = null;
        }, timeout)
    }
}