明源云笔试题

1. 如何解决跨域问题?

解决方案

2. 分割数字,99999999.232332 -> 99,999,999.232332

调用 api

function formatNum(num) {
  return num.toLocaleString();
}

正则

function formatNum(num) {
  // 非单词边界,但是感觉不太语义话
  return `${num}`.replace(/(\B)(?=(\d{3})+\.)/g, '$1,');
}

function formatNum(num) {
  return `${num}`.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  // `${num}`.replace(/(\d)(?=(\d{3})+\.)/g, '$&,');
}

TIP

  1. $& - 正则表达式匹配的文本
  2. $` - 匹配文本的左侧内容
  3. $' - 匹配文本的右侧内容
  4. $1-9 - 分组

for 循环

function formatNum(num) {
  let arr = String(num).split('.');
  let integer = arr[0];
  let count = 0,
    temp = [];
  for (let i = integer.length - 1; i >= 0; i--) {
    count++;
    temp.push(integer[i]);
    if (count % 3 === 0 && i !== 0) {
      temp.push(',');
    }
  }
  integer = temp.reverse().join('');
  return arr[1] ? `${integer}.${arr[1]}` : integer;
}

while 循环 + slice

function formatNum(num) {
  let arr = Sting(num).split('.');
  let integer = arr[0];
  let count = integer.length,
    len = integer.length,
    temp = [];
  while (count >= 3) {
    temp.unshift(integer.slice(count - 3, count));
    count -= 3;
  }
  len % 3 && temp.unshift(integer.slice(0, len % 3));
  integer = temp.toString();
  return arr[1] ? `${integer}.${arr[1]}` : integer;
}

3. 提取 id,变成一维数组。

变量 arr 是一个 object 数组,有两个属性。id、children。

从 arr 中提取子孙元素的 id 组成一个一维数组, 如[1, 2, 3, 4 ....]

var arr = [
  {
    id: 1,
    children: [...] || null
  }
]
function deep(list, flatten = []) {
  if (!Array.isArray(list)) return list;
  for (let i = 0; i < list.length; i++) {
    let node = list[i];
    flatten.push(node.id);
    if (Array.isArray(node.children)) {
      deep(node.children, flatten);
    }
  }
  return flatten;
}

// 测试一下
let arr = [
  {
    id: 1,
    children: [
      {
        id: 2,
        children: [
          {
            id: 3,
            children: [
              {
                id: 4,
                children: null
              }
            ]
          }
        ]
      }
    ]
  },
  {
    id: 5,
    children: null
  }
];

deep(arr); // [ 1, 2, 3, 4, 5 ]

4. 不可变数组的范围求和

给定一个整数数组 nums, 计算出从第 i 个元素到第 j 个元素的和(i <= j), 包括 nums[i] 和 nums[j]

注意:数组可能规模很大(比如超过 10000 个数),注意运行时间

🌰:

const nums = Object.freeze([-2, 0, 3, -5, 2, -1]);
sumRange(0, 2); // 1
sumRange(2, 5); // -1
sumRange(0, 5); // 3

普通 for 循环

function sumRange(start, end) {
  const nums = Object.freeze([-2, 0, 3, -5, 2, -1]);
  let sum = 0;
  for (let i = start; i <= end; i++) {
    sum += nums[i];
  }
  return sum;
}

双指针

function sumRange(start, end) {
  const nums = Object.freeze([-2, 0, 3, -5, 2, -1]);
  let sum = 0;
  while (start <= end) {
    let left = nums[start];
    let right = nums[end];
    sum += left + right;
    start++, end--;
  }
  return sum;
}

实现一个 LazyMan

实现一个 LazyMan,可以按照以下方式调用:

LazyMan('Hank');

// 输出 ⬇️

Hi, This is Hank!

LazyMan('Hank').sleep(5).eat('dinner');

// 输出 ⬇️

Hi, This is Hank!
// 等待5秒
Weak up after 10
Eat dinner ~

LazyMan('Hank').eat('dinner').eat('supper');

// 输出 ⬇️

Hi, this is Hank!
Eat dinner ~
Eat supper ~

LazyMan('Hank').sleepFirst(5).eat('supper');

// 输出 ⬇️

// 等待5秒
Wake up after 5
Hi, this is Hank!
Eat supper ~
class PersonGenerator {
  constructor(name) {
    this.taskQueue = [];
    this.runTimer = null;
    this.sayHi(name);
  }

  run() {
    this.runTimer && clearTimeout(this.runTimer);
    this.runTimer = setTimeout(async () => {
      for (const asyncFn of this.taskQueue) {
        await asyncFn();
      }
      this.taskQueue.length = 0;
      this.runTimer = null;
    });
    return this;
  }

  sayHi(name) {
    this.taskQueue.push(async () => console.log(`Hi, this is ${name}!`));
    return this.run();
  }

  eat(food) {
    this.taskQueue.push(async () => console.log(`😋 Eat ${food}~~`));
    return this.run();
  }

  sleep(time) {
    this.taskQueue.push(async () => {
      console.log(`Sleep ${time} seconds 😪`);
      await this._timeout(time);
    });
    return this.run();
  }

  sleepFirst(time) {
    this.taskQueue.splice(-1, 0, async () => {
      console.log(`Sleep ${time} seconds 😪`);
      await this._timeout(time);
    });
    return this.run();
  }

  async _timeout(time) {
    return new Promise(resolve => {
      setTimeout(resolve, time * 1000);
    });
  }
}

const Person = name => new PersonGenerator(name);

// Person('kk').sleepFirst(3).eat('fruit').sleep(10).eat('apple');

Person('kk')
  .sleepFirst(3)
  .sleepFirst(5)
  .eat('apple');
Last Updated:
Contributors: kk