lru-memoizer.test.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. var memoizer = require('./..');
  2. var assert = require('chai').assert;
  3. describe('lru-memoizer', function () {
  4. var loadTimes = 0, memoized;
  5. beforeEach(function () {
  6. loadTimes = 0;
  7. memoized = memoizer({
  8. load: function (a, b, callback) {
  9. loadTimes++;
  10. return setTimeout(function () {
  11. if (a === 0) {
  12. return callback(new Error('a cant be 0'));
  13. }
  14. callback(null, a+b);
  15. }, 10);
  16. },
  17. hash: function (a, b) {
  18. return a + '-' + b;
  19. },
  20. max: 10
  21. });
  22. });
  23. it('should cache the result of an async function', function (done) {
  24. memoized(1,2, function (err, result) {
  25. assert.isNull(err);
  26. assert.strictEqual(result, 3);
  27. assert.strictEqual(loadTimes, 1);
  28. memoized(1,2, function (err, result) {
  29. assert.isNull(err);
  30. assert.strictEqual(result, 3);
  31. assert.strictEqual(loadTimes, 1);
  32. done();
  33. });
  34. });
  35. });
  36. it('should use the hash function for keys', function (done) {
  37. memoized(1, 2, function () {
  38. memoized(2,3, function () {
  39. assert.includeMembers(memoized.keys(), ['1-2', '2-3']);
  40. done();
  41. });
  42. });
  43. });
  44. it('should not cache errored funcs', function (done) {
  45. memoized(0, 2, function (err) {
  46. assert.isNotNull(err);
  47. assert.notInclude(memoized.keys(), ['0-2']);
  48. done();
  49. });
  50. });
  51. it('should expose the hash function', function() {
  52. assert.equal(memoized.hash(0, 2), '0-2');
  53. });
  54. it('should expose the load function', function(done) {
  55. memoized.load(1, 2, (err, result) => {
  56. assert.equal(result, 3);
  57. done();
  58. });
  59. });
  60. it('should expose the max prop', function() {
  61. assert.equal(memoized.max, 10);
  62. });
  63. it('should allow to del a key', function(done) {
  64. memoized(1,2, () => {
  65. assert.strictEqual(loadTimes, 1);
  66. memoized.del(1,2);
  67. memoized(1,2, (err, result) => {
  68. assert.isNull(err);
  69. assert.strictEqual(result, 3);
  70. assert.strictEqual(loadTimes, 2);
  71. done();
  72. });
  73. });
  74. });
  75. });