Garrett Johnson 5 gadi atpakaļ
vecāks
revīzija
1c95216396
2 mainītis faili ar 40 papildinājumiem un 3 dzēšanām
  1. 5 1
      src/utilities/LRUCache.js
  2. 35 2
      test/LRUCache.test.js

+ 5 - 1
src/utilities/LRUCache.js

@@ -148,7 +148,11 @@ class LRUCache {
 
 			}
 
-			let nodesToUnload = Math.min( targetSize * unloadPercent, unused );
+			// address corner cases where the minSize might be zero or smaller than maxSize - minSize,
+			// which would result in a very small or no items being unloaded.
+			const unusedExcess = Math.min( excess, unused );
+			const maxUnload = Math.max( targetSize * unloadPercent, unusedExcess * unloadPercent );
+			let nodesToUnload = Math.min( maxUnload, unused );
 			nodesToUnload = Math.ceil( nodesToUnload );
 
 			const removedItems = itemList.splice( 0, nodesToUnload );

+ 35 - 2
test/LRUCache.test.js

@@ -49,13 +49,46 @@ describe( 'LRUCache', () => {
 		cache.add( {}, () => {} );
 
 		expect( cache.isFull() ).toEqual( true );
-		cache.unloadUnusedContent( 0.25, null );
+		cache.unloadUnusedContent( null );
 		expect( cache.isFull() ).toEqual( true );
 		cache.markAllUnused();
-		cache.unloadUnusedContent( 0.25, null );
+		cache.unloadUnusedContent( null );
 
 		expect( cache.isFull() ).toEqual( false );
 
 	} );
 
+	it( 'should sort before unloading', () => {
+
+		const cache = new LRUCache();
+		cache.minSize = 0;
+		cache.maxSize = 10;
+		cache.unloadPercent = 1;
+
+		const arr = [];
+		const unloadCallback = item => {
+
+			arr.push( item.priority );
+
+		};
+
+		const P1 = { priority: 1 };
+		const P2 = { priority: 2 };
+		const P3 = { priority: 3 };
+		const P4 = { priority: 4 };
+
+		cache.add( P1, unloadCallback );
+		cache.add( P2, unloadCallback );
+		cache.add( P3, unloadCallback );
+		cache.add( P4, unloadCallback );
+
+		cache.markAllUnused();
+		cache.markUsed( P2 );
+		cache.markUsed( P3 );
+
+		cache.unloadUnusedContent( ( a, b ) => b.priority - a.priority );
+		expect( arr ).toEqual( [ 4, 1 ] );
+
+	} );
+
 } );