Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

memoization.js 1.5KB

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