20230218 西安腾讯乐享

120 阅读1分钟

一面(1h)

编程题

查找字符串中出现最多的字符和个数

// 例如:abbcccddddd -> 字符最多的是 d,出现了 5 次
// 输出 => d,5
// 实现 getMaxCharacter 函数
function getMaxCharacter(str) {
    // 你的代码
    const enumCount = {};
    for (let i = 0; i < str.length; i++) {
        if (enumCount[str[i]]) {
            enumCount[str[i]]++;
        } else {
            enumCount[str[i]] = 1;
        }
    }
    let s = '';
    let count = 0;
    const arr = Object.keys(enumCount).forEach(key => {
        if (enumCount[key] > count) {
            s = `${key},${enumCount[key]}`;
            count = enumCount[key]
        }
    })
    return s;
}
getMaxCharacter('abbcccddddd');

给定多个 Promise,实现一个 promiseConcurrency 函数,支持控制 Promise 的并发数量

// 例如 concurrency 传入 4,则表示同短时间内只能有 4 个 task 在运行,
// 等待全部 Promise 执行完后,返回所有结果
// 传入 promiseConcurrency 里的 task 函数
const task = (time) => () => new Promise(resolve => {
  setTimeout(() => {
    console.log(time);
    resolve(time);
  }, time);
});
// tasks 为上文的 task 函数数组,返回一个 promise
// concurrency 为并发次数,指定同一时间可以运行的 promise 数量
// 实现 promiseConcurrency 函数
function promiseConcurrency(tasks = [], concurrency = 0) {
  // 你的代码
  return new Promise((resolve) => {
    if (tasks.length === 0) {
      resolve();
      return;
    }
    let nextIndex = 0;
    let fulfilledCount = 0;
    const next = () => {
      const task = tasks[nextIndex];
      nextIndex += 1;
      task().then(() => {
        fulfilledCount += 1;
        if (nextIndex < tasks.length) {
          next();
        } else if (fulfilledCount === tasks.length) {
          resolve();
        }
      });
    };
    for (let i = 0; i < concurrency && i < tasks.length; i += 1) {
      next();
    }
  });
}
// 输出结果
// 2000 // 第一次输出
// 3000 3000 3000 1000 // 第二次输出
// 2000 // 第三次输出
// [ 3000, 3000, 3000, 2000, 1000, 2000 ] // 最后输出
promiseConcurrency([
  task(3000),
  task(3000),
  task(3000),
  task(2000),
  task(1000),
  task(2000),
], 4).then((res) => {
  console.log('all result: ', res);
});

问答

  1. 场景题:上传多个图片,要求前端不要开太大的口子,控制上传的并发量,控制同时上传到的数量,如何实现(编程题第二题)。

  2. 怎么理解事件循环。

  3. Vue 有哪些 Api 是基于微队列实现的,为什么需要这么做。

  4. 开发一个npm包供用户使用,用户可能通过代码 import ,也可能是通过 CDN 引入。如果是工具包,也可能支持在服务器端使用。如何实现一个 npm 包,同时支持 import,CDN引入,也可以在服务器端用。

  5. 微前端是怎么实现的。

  6. 开发过程中,可能遇到一些安全问题,有哪些前端的安全问题是需要去考虑的。

本文由mdnice多平台发布