[js]一道缓存类面试题

2018-03-03  本文已影响0人  一桶冷水

在开发过程中踩了一个坑,觉得挺有意思,就顺手编成了一道题。

// Cache是一个缓存类,使用时先在new方法中注册获取数据的方法,然后可通过get方法获取数据,
// 并且只有第一次调用get会真正调用new中注册的方法获取数据,以后都直接从缓存中返回。

function Cache () {
    this.store = {}
}

Cache.prototype.add = function (name, fn) {
    if (!name || !fn || typeof fn !== 'function') {
        return
    }
    this.store[name] = {name, fn, data: {}}
}

Cache.prototype.get = function (name, key) {
    const self = this.store[name]
    key = key || 1
    if (self.data[key]) {
        return Promise.resolve(self.data[key])
    }
    return self.fn(key).then(data => {
        self.data[key] = data
        return data
    })
}

Cache.prototype.clear = function (name, key) {
    this.store[name].data[key] = null
}

Cache.prototype.clearAll = function (name) {
    this.store[name].data = {}
}

// 1.下面的代码说明Cache的实现存在一个bug,尝试修复它

const c = new Cache()

c.add('foo', function (key) {
    return Promise.resolve([1])
})

c.get('foo').then(
    list0 => {
        console.log(list0)
        list0.push(2)
        return c.get('foo')
    }).then(
    list1 => {
        console.log(list1)
        list1.push(3)
        return c.get('foo')
    }).then(
    list2 => {
        console.log(list2)
    })

// 2.对以上代码提出一些改进意见
// 3.当同时对同一个name,同一个key发起多个get,且缓存不存在时,会导致fn多次执行,优化这个问题

以下是解答:

Cache.prototype.get = function (name, key) {
  const self = this.store[name]
  if (self.data[key]) {
    return Promise.resolve(JSON.parse(self.data[key]))
  }
  return self.fn(key).then(data => {
    self.data[key] = JSON.stringify(data)
    return data
  })
}

我在刚编出这道的时候觉得不过就是一个考察return返回引用的题目,并不多难,但是在问过几个人以后才发现没那么简单。首先需要对使用原型链构造类有基本的了解,对于那些如果是仅仅只是实现一下业务逻辑,不做任何抽象和封装的ctrl+v工程师而言恐怕确实不需要懂。其次是Promise和ES6语法,相对来说这些也是比较新的东西。

为什么人与人之间差别就那么大呢?同一个技术点对有的人来说是不必多说的基础,对于另一些人来说却是天方夜谭…

上一篇 下一篇

猜你喜欢

热点阅读