memoization.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict'
  2. const LRU = require('lru-cache')
  3. const MAX_SIZE = 50 * 1024 * 1024 // 50MB
  4. const MAX_AGE = 3 * 60 * 1000
  5. const MEMOIZED = new LRU({
  6. max: MAX_SIZE,
  7. maxAge: MAX_AGE,
  8. length: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length,
  9. })
  10. module.exports.clearMemoized = clearMemoized
  11. function clearMemoized () {
  12. const old = {}
  13. MEMOIZED.forEach((v, k) => {
  14. old[k] = v
  15. })
  16. MEMOIZED.reset()
  17. return old
  18. }
  19. module.exports.put = put
  20. function put (cache, entry, data, opts) {
  21. pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data })
  22. putDigest(cache, entry.integrity, data, opts)
  23. }
  24. module.exports.put.byDigest = putDigest
  25. function putDigest (cache, integrity, data, opts) {
  26. pickMem(opts).set(`digest:${cache}:${integrity}`, data)
  27. }
  28. module.exports.get = get
  29. function get (cache, key, opts) {
  30. return pickMem(opts).get(`key:${cache}:${key}`)
  31. }
  32. module.exports.get.byDigest = getDigest
  33. function getDigest (cache, integrity, opts) {
  34. return pickMem(opts).get(`digest:${cache}:${integrity}`)
  35. }
  36. class ObjProxy {
  37. constructor (obj) {
  38. this.obj = obj
  39. }
  40. get (key) {
  41. return this.obj[key]
  42. }
  43. set (key, val) {
  44. this.obj[key] = val
  45. }
  46. }
  47. function pickMem (opts) {
  48. if (!opts || !opts.memoize)
  49. return MEMOIZED
  50. else if (opts.memoize.get && opts.memoize.set)
  51. return opts.memoize
  52. else if (typeof opts.memoize === 'object')
  53. return new ObjProxy(opts.memoize)
  54. else
  55. return MEMOIZED
  56. }