cache_spec.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var Cache = require('src/cache')
  2. /**
  3. * Debug function to assert cache state
  4. *
  5. * @param {Cache} cache
  6. */
  7. function toString (cache) {
  8. var s = ''
  9. var entry = cache.head
  10. while (entry) {
  11. s += String(entry.key) + ':' + entry.value
  12. entry = entry.newer
  13. if (entry) {
  14. s += ' < '
  15. }
  16. }
  17. return s
  18. }
  19. describe('Cache', function () {
  20. var c = new Cache(4)
  21. it('put', function () {
  22. c.put('adam', 29)
  23. c.put('john', 26)
  24. c.put('angela', 24)
  25. c.put('bob', 48)
  26. expect(c.size).toBe(4)
  27. expect(toString(c)).toBe('adam:29 < john:26 < angela:24 < bob:48')
  28. })
  29. it('put with same key', function () {
  30. var same = new Cache(4)
  31. same.put('john', 29)
  32. same.put('john', 26)
  33. same.put('john', 24)
  34. same.put('john', 48)
  35. expect(same.size).toBe(1)
  36. expect(toString(same)).toBe('john:48')
  37. })
  38. it('get', function () {
  39. expect(c.get('adam')).toBe(29)
  40. expect(c.get('john')).toBe(26)
  41. expect(c.get('angela')).toBe(24)
  42. expect(c.get('bob')).toBe(48)
  43. expect(toString(c)).toBe('adam:29 < john:26 < angela:24 < bob:48')
  44. expect(c.get('angela')).toBe(24)
  45. // angela should now be the tail
  46. expect(toString(c)).toBe('adam:29 < john:26 < bob:48 < angela:24')
  47. })
  48. it('expire', function () {
  49. c.put('ygwie', 81)
  50. expect(c.size).toBe(4)
  51. expect(toString(c)).toBe('john:26 < bob:48 < angela:24 < ygwie:81')
  52. expect(c.get('adam')).toBeUndefined()
  53. })
  54. it('shift', function () {
  55. var shift = new Cache(4)
  56. shift.put('adam', 29)
  57. shift.put('john', 26)
  58. shift.put('angela', 24)
  59. shift.put('bob', 48)
  60. shift.shift()
  61. shift.shift()
  62. shift.shift()
  63. expect(shift.size).toBe(1)
  64. expect(toString(shift)).toBe('bob:48')
  65. })
  66. })