腾讯面试题整理(其一)

设计一个函数,输入数字,输出转换成千分位显示,如 1234567890=>1,234,567,890

function handlerNums(num) {
     
	num = '' + num
	const arr = num.split('').reverse()
	let result = []
	for (let i = 0, len = arr.length; i < len; i++) {
     
		result.unshift(arr[i])
		if (i > 0 && i < len - 1 && i % 3 == 2) {
     
			result.unshift(',')
		}
	}
	return result.join('')
}

实现防抖函数 debounce 和节流函数 throttle

let count = 0;
let dom = document.getElementById("app");
let input = document.getElementById("input");

function debounce(cb, wait = 1000) {
     
  let timer = null;
  return function() {
     
    const args = [...arguments];
    clearTimeout(timer);
    timer = setTimeout(() =>{
     
      cb.apply(this,args);
    },wait);
  }
}

function throttle(cb, wait) {
     
  let timer = null;
  let flag = false;
  return function() {
     
    if(flag) return;
    const args = [...arguments];
    if(!flag) {
     
      flag= true;
      timer = setTimeout(() =>{
     
        cb.apply(this, args);
        flag = false;
      },wait);
    }
  }
}

input.addEventListener('keyup',throttle(function(){
     
  console.log(this)
  dom.innerHTML = this.value
},5000))

实现一个 LRU 缓存模块

class LRUModule {
     
  constructor() {
     
    this.idCatch ={
     };
    this.timecatch = [];
  }

  add(data) {
     
    if(this.idCatch[data.id]){
     
      this.get(data.id);
      return;
    }
    this.idCatch[data.id] = data;
    if(this.timeCatch.length === 10){
     
      const id = this.timecatch[e];
      delete this.idCatch.id;
      this.sort(e);
    }
    this.timeCatch.push(data.id);
    this.idCatch[data.id].index = this.timeCatch.length - 1;
  }

  get(id){
     
    let data = this.idcatch[id];
    const i = data.index;
    this.sort(i);
    this.timeCatch.push(data.id);
    data.index = this.timeCatch. length;
    return data;
  }

  sort(index) {
     
    this.timecatch.splice(index,1);
    for( let i = index; i < this.timecatch. length; i++){
     
      const id = this.timecatch[i];
      this.idcatch[id].index--;
    }
  }
}
let obj = new LRUModule();

你可能感兴趣的:(腾讯面试题整理(其一))