手写题

98 阅读2分钟

实现数组乱序输出

  • 方法1 洗牌算法
function shuffleArray(array) {
  let currentIndex = array.length;
  let temporaryValue;
  let randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// 使用示例
let myArray = [1, 2, 3, 4, 5];
console.log(shuffleArray(myArray));
// 从原数组中随机抽取一个元素放入新数组
function shuffle1(arr) {
    let res = [], random
    while (arr.length > 0) {
        random = parseInt(Math.random() * arr.length)
        res.push(arr.splice(random, 1)[0])
        
    }
    return res
}

shuffle1([2,3,6,2,6,2]) // [6, 3, 2, 2, 2, 6]

  • 方法2
function shuffleArray(array) {
  return array.sort(function() {
    return 0.5 - Math.random();
  });
}

// 使用示例
let myArray = [1, 2, 3, 4, 5];
console.log(shuffleArray(myArray));

js实现数组扁平化

  • 使用递归方式
function flatten(arr) {
  let result = [];
  arr.forEach(item => {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result.push(item);
    }
  });
  return result;
}

const arr = [1, [2, [3, 4]], 5];
console.log(flatten(arr)); // [1, 2, 3, 4, 5]
  • 使用reduce方法
function flatten(arr) {
  return arr.reduce((prev, cur) => {
    return prev.concat(Array.isArray(cur) ? flatten(cur) : cur);
  }, []);
}

const arr = [1, [2, [3, 4]], 5];
console.log(flatten(arr)); // [1, 2, 3, 4, 5]
  • 使用ES6的展开运算符
function flatten(arr) {
  while (arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
}

const arr = [1, [2, [3, 4]], 5];
console.log(flatten(arr)); // [1, 2, 3, 4, 5]
  • 使用Generator函数
function* flatten(arr) {
  for (const item of arr) {
    if (Array.isArray(item)) {
      yield* flatten(item);
    } else {
      yield item;
    }
  }
}

实现一个 lodash 的 get 方法

/**
 * object (Object): 要检索的对象。
 * path (string): 要获取属性的路径。
 * [defaultValue] (*): 如果解析值不存在,会返回 default。
 */
function _get(object, path, default) {
    // 在这里实现
}

// === 用例 === 

const object = { 'a': [{ 'b': { 'c': 3 } }] };

_get(object, 'a[0].b.c');
// => 3

_get(object, 'a.b.c', 'default');
// => 'default'

实现一个 EventEmitter

class EventEmitter {
    // 在这里实现
}

const eventEmitter = new EventEmitter()

function callback() {
    console.log('hit!')
 }
 
 // 监听事件, 其中有一个 once 单次监听
eventEmitter.on('custom-event', callback)
eventEmitter.once('custom-event', callback)

// 连续触发两次
eventEmitter.emit('custom-event')
eventEmitter.emit('custom-event')
// 预期输出 3 次 "hit!"

// 删除并再次=触发
eventEmitter.removeListener('custom-event');
eventEmitter.emit('custom-event')
// 预期没有输出

写个函数用来渲染这个结构

const renderJSON = {
    type: 'div',
    props: {
        className: '',
    },
    childrens:[
        {
            type: 'p',
            props: {
               text:'xxxxx'
            },
            childrens:[]
        }
    ]
}

设计一个 Cache

支持下列两个基本操作:

  • set(id, object), 根据id设置对象;
  • get(id): 根据id得到一个对象; 同时它有下面几个性质:
  1. x秒自动过期, 如果cache内的对象, x秒内没有被get或者set过, 则会自动过期;
  2. 对象数限制, 该cache可以设置一个n, 表示cache最多能存储的对象数;
  3. LRU置换, 当进行set操作时, 如果此时cache内对象数已经到达了n个, 则cache自动将最久未被使用过的那个对象剔除, 腾出空间放置新对象;