Skip to content

Commit

Permalink
chore: make clearCacheEntries DRYer
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmadshaheer committed Dec 2, 2024
1 parent 92aca21 commit 44a3f1b
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions frontend/src/hooks/useTimezoneFormatter/useTimezoneFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,19 @@ function useTimezoneFormatter({
cache.clear();
}, [cache, userTimezone]);

const clearExpiredEntries = useCallback(() => {
const clearCacheEntries = useCallback(() => {
if (cache.size <= CACHE_SIZE_LIMIT) return;

// Sort entries by timestamp (oldest first)
const sortedEntries = Array.from(cache.entries()).sort(
(a, b) => a[1].timestamp - b[1].timestamp,
);

// Calculate how many entries to remove
const entriesToRemove = Math.floor(cache.size * CACHE_CLEANUP_PERCENTAGE);
// Calculate how many entries to remove (50% or overflow, whichever is larger)
const entriesToRemove = Math.max(
Math.floor(cache.size * CACHE_CLEANUP_PERCENTAGE),
cache.size - CACHE_SIZE_LIMIT,
);

// Remove oldest entries
sortedEntries.slice(0, entriesToRemove).forEach(([key]) => cache.delete(key));
Expand All @@ -75,22 +78,12 @@ function useTimezoneFormatter({

// Clear expired entries and enforce size limit
if (cache.size > CACHE_SIZE_LIMIT) {
clearExpiredEntries();

// If still over limit, remove oldest entries
const entriesToDelete = cache.size - CACHE_SIZE_LIMIT;
if (entriesToDelete > 0) {
const entries = Array.from(cache.entries());
entries
.sort((a, b) => a[1].timestamp - b[1].timestamp)
.slice(0, entriesToDelete)
.forEach(([key]) => cache.delete(key));
}
clearCacheEntries();
}

return formattedValue;
},
[cache, clearExpiredEntries, userTimezone],
[cache, clearCacheEntries, userTimezone],
);

return { formatTimezoneAdjustedTimestamp };
Expand Down

0 comments on commit 44a3f1b

Please sign in to comment.