LRUCache.test.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { LRUCache } from '../src/utilities/LRUCache.js';
  2. describe( 'LRUCache', () => {
  3. it( 'should not allow the same object to be added more than once.', () => {
  4. const cache = new LRUCache();
  5. const A = {};
  6. expect( cache.add( A, () => {} ) ).toEqual( true );
  7. expect( cache.add( A, () => {} ) ).toEqual( false );
  8. expect( cache.remove( A ) ).toEqual( true );
  9. expect( cache.remove( A ) ).toEqual( false );
  10. } );
  11. it( 'should not allow adding if the cache is full.', () => {
  12. const cache = new LRUCache();
  13. cache.minSize = cache.maxSize = 1;
  14. expect( cache.isFull() ).toEqual( false );
  15. cache.add( {}, () => {} );
  16. expect( cache.add( {}, () => {} ) ).toEqual( false );
  17. expect( cache.isFull() ).toEqual( true );
  18. } );
  19. it( 'should fire the callback when removing an item.', () => {
  20. const cache = new LRUCache();
  21. const A = {};
  22. let called = false;
  23. cache.add( A, () => called = true );
  24. expect( called ).toEqual( false );
  25. cache.remove( A );
  26. expect( called ).toEqual( true );
  27. } );
  28. it( 'should mark an item as used when adding.', () => {
  29. const cache = new LRUCache();
  30. cache.minSize = 0;
  31. cache.maxSize = 1;
  32. cache.add( {}, () => {} );
  33. expect( cache.isFull() ).toEqual( true );
  34. cache.unloadUnusedContent( null );
  35. expect( cache.isFull() ).toEqual( true );
  36. cache.markAllUnused();
  37. cache.unloadUnusedContent( null );
  38. expect( cache.isFull() ).toEqual( false );
  39. } );
  40. it( 'should sort before unloading', () => {
  41. const cache = new LRUCache();
  42. cache.unloadPriorityCallback = item => item.priority;
  43. cache.minSize = 0;
  44. cache.maxSize = 10;
  45. cache.unloadPercent = 1;
  46. const arr = [];
  47. const unloadCallback = item => {
  48. arr.push( item.priority );
  49. };
  50. const P1 = { priority: 1 };
  51. const P2 = { priority: 2 };
  52. const P3 = { priority: 3 };
  53. const P4 = { priority: 4 };
  54. cache.add( P1, unloadCallback );
  55. cache.add( P2, unloadCallback );
  56. cache.add( P3, unloadCallback );
  57. cache.add( P4, unloadCallback );
  58. cache.markAllUnused();
  59. cache.markUsed( P2 );
  60. cache.markUsed( P3 );
  61. cache.unloadUnusedContent();
  62. expect( arr ).toEqual( [ 4, 1 ] );
  63. } );
  64. } );