Last active
December 20, 2018 20:42
-
-
Save bencbartlett/09406e22a7991a590d2b308f7ac6a0b7 to your computer and use it in GitHub Desktop.
GlobalCache.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class $ { // $ = cash = cache... get it? :D | |
static set<T extends HasRef, K extends keyof T>(thing: T, key: K, | |
callback: () => (T[K] & (undefined | HasID | HasID[])), | |
timeout = CACHE_TIMEOUT): void { | |
const cacheKey = thing.ref + '$' + key; | |
if (!_cache.things[cacheKey] || Game.time > _cache.expiration[cacheKey]) { | |
// Recache if new entry or entry is expired | |
_cache.things[cacheKey] = callback(); | |
_cache.expiration[cacheKey] = getCacheExpiration(timeout, Math.ceil(timeout / 10)); | |
} else { | |
// Refresh structure list by ID if not already done on current tick | |
if ((_cache.accessed[cacheKey] || 0) < Game.time) { | |
if (_.isArray(_cache.things[cacheKey])) { | |
_cache.things[cacheKey] = _.compact(_.map(_cache.things[cacheKey], s => Game.getObjectById(s.id))) as HasID[]; | |
} else { | |
_cache.things[cacheKey] = Game.getObjectById((_cache.things[cacheKey]).id) as HasID; | |
} | |
_cache.accessed[cacheKey] = Game.time; | |
} | |
} | |
thing[key] = _cache.things[cacheKey] as T[K] & (undefined | HasID | HasID[]); | |
} | |
static refresh<T extends Record<K, undefined | HasID | HasID[]>, K extends string>(thing: T, ...keys: K[]): void { | |
_.forEach(keys, function (key) { | |
if (thing[key]) { | |
if (_.isArray(thing[key])) { | |
thing[key] = _.compact(_.map(thing[key] as HasID[], s => Game.getObjectById(s.id))) as T[K]; | |
} else { | |
thing[key] = Game.getObjectById((<HasID>thing[key]).id) as T[K]; | |
} | |
} | |
}); | |
} | |
static refreshRoom<T extends { room: Room }>(thing: T): void { | |
thing.room = Game.rooms[thing.room.name]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment