Tencent interview questions finishing (Part 1)

Design a function, input a number, and convert the output into a thousandth display, such as 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('')
}

Implement the anti-shake function debounce and throttle function 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))

Implement an LRU cache module

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();

Guess you like

Origin blog.csdn.net/qq_40289624/article/details/113244088