腾讯面试题整理(其一)

本文整理了腾讯面试中出现的三道题目,包括将数字转换为千分位显示的函数,防抖(debounce)和节流(throttle)函数的实现,以及如何设计一个LRU缓存模块。这些题目涵盖了函数处理、性能优化和数据结构等方面的知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计一个函数,输入数字,输出转换成千分位显示,如 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();
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值