From d792c6764a0e4638b1ca0a7da25a9326cc44a9c9 Mon Sep 17 00:00:00 2001 From: Gus Caplan Date: Sat, 26 Aug 2017 05:48:31 -0700 Subject: [PATCH] ChannelStore LRU (#1832) --- src/stores/ChannelStore.js | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/stores/ChannelStore.js b/src/stores/ChannelStore.js index cffa642bb..657af240a 100644 --- a/src/stores/ChannelStore.js +++ b/src/stores/ChannelStore.js @@ -3,12 +3,51 @@ const DMChannel = require('../structures/DMChannel'); const GroupDMChannel = require('../structures/GroupDMChannel'); const Constants = require('../util/Constants'); +const kLru = Symbol('LRU'); +const lruable = ['group', 'dm']; + /** * Stores channels. * @private * @extends {DataStore} */ class ChannelStore extends DataStore { + constructor(iterable, options = {}) { + super(iterable); + + if (options.lru) { + const lru = this[kLru] = []; + lru.add = item => { + lru.remove(item); + lru.unshift(item); + while (lru.length > options.lru) this.remove(lru[lru.length - 1]); + }; + lru.remove = item => { + const index = lru.indexOf(item); + if (index > -1) lru.splice(index, 1); + }; + } + } + + get(key, peek = false) { + const item = super.get(key); + if (!item || !lruable.includes(item.type)) return item; + if (!peek && this[kLru]) this[kLru].add(key); + return item; + } + + set(key, val) { + if (this[kLru] && lruable.includes(val.type)) this[kLru].add(key); + return super.set(key, val); + } + + delete(key) { + const item = this.get(key, true); + if (!item) return false; + if (this[kLru] && lruable.includes(item.type)) this[kLru].remove(key); + return super.delete(key); + } + create(data, guild, cache = true) { const existing = this.get(data.id); if (existing) return existing;