foreach.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. var test = require('tap').test
  2. var LRU = require('../')
  3. test('forEach', function (t) {
  4. var l = new LRU(5)
  5. for (var i = 0; i < 10; i ++) {
  6. l.set(i.toString(), i.toString(2))
  7. }
  8. var i = 9
  9. l.forEach(function (val, key, cache) {
  10. t.equal(cache, l)
  11. t.equal(key, i.toString())
  12. t.equal(val, i.toString(2))
  13. i -= 1
  14. })
  15. // get in order of most recently used
  16. l.get(6)
  17. l.get(8)
  18. var order = [ 8, 6, 9, 7, 5 ]
  19. var i = 0
  20. l.forEach(function (val, key, cache) {
  21. var j = order[i ++]
  22. t.equal(cache, l)
  23. t.equal(key, j.toString())
  24. t.equal(val, j.toString(2))
  25. })
  26. t.equal(i, order.length);
  27. t.end()
  28. })
  29. test('keys() and values()', function (t) {
  30. var l = new LRU(5)
  31. for (var i = 0; i < 10; i ++) {
  32. l.set(i.toString(), i.toString(2))
  33. }
  34. t.similar(l.keys(), ['9', '8', '7', '6', '5'])
  35. t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
  36. // get in order of most recently used
  37. l.get(6)
  38. l.get(8)
  39. t.similar(l.keys(), ['8', '6', '9', '7', '5'])
  40. t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
  41. t.end()
  42. })
  43. test('all entries are iterated over', function(t) {
  44. var l = new LRU(5)
  45. for (var i = 0; i < 10; i ++) {
  46. l.set(i.toString(), i.toString(2))
  47. }
  48. var i = 0
  49. l.forEach(function (val, key, cache) {
  50. if (i > 0) {
  51. cache.del(key)
  52. }
  53. i += 1
  54. })
  55. t.equal(i, 5)
  56. t.equal(l.keys().length, 1)
  57. t.end()
  58. })
  59. test('all stale entries are removed', function(t) {
  60. var l = new LRU({ max: 5, maxAge: -5, stale: true })
  61. for (var i = 0; i < 10; i ++) {
  62. l.set(i.toString(), i.toString(2))
  63. }
  64. var i = 0
  65. l.forEach(function () {
  66. i += 1
  67. })
  68. t.equal(i, 5)
  69. t.equal(l.keys().length, 0)
  70. t.end()
  71. })
  72. test('expires', function (t) {
  73. var l = new LRU({
  74. max: 10,
  75. maxAge: 50
  76. })
  77. for (var i = 0; i < 10; i++) {
  78. l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined))
  79. }
  80. var i = 0
  81. var order = [ 8, 6, 4, 2, 0 ]
  82. setTimeout(function () {
  83. l.forEach(function (val, key, cache) {
  84. var j = order[i++]
  85. t.equal(cache, l)
  86. t.equal(key, j.toString())
  87. t.equal(val, j.toString(2))
  88. })
  89. t.equal(i, order.length);
  90. setTimeout(function () {
  91. var count = 0;
  92. l.forEach(function (val, key, cache) { count++; })
  93. t.equal(0, count);
  94. t.end()
  95. }, 25)
  96. }, 26)
  97. })