|
| 1 | +package com.igorwojda.cache.advancedlru |
| 2 | + |
| 3 | +import org.amshove.kluent.shouldBeEqualTo |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import java.util.* |
| 6 | + |
| 7 | +class AdvancedLRUCache(private val capacity: Int) { |
| 8 | + fun put(key: String, value: Int, priority: Int, expiryTime: Long) { |
| 9 | + TODO("Add your solution here") |
| 10 | + } |
| 11 | + |
| 12 | + fun get(key: String): Int? { |
| 13 | + TODO("Add your solution here") |
| 14 | + } |
| 15 | + |
| 16 | + private fun remove(key: String) { |
| 17 | + TODO("Add your solution here") |
| 18 | + } |
| 19 | + |
| 20 | + private fun clearCache() { |
| 21 | + TODO("Add your solution here") |
| 22 | + } |
| 23 | + |
| 24 | + private data class CacheItem( |
| 25 | + val key: String, |
| 26 | + var value: Int, |
| 27 | + var priority: Int, |
| 28 | + var expiryTime: Long, |
| 29 | + ) : Comparable<CacheItem> { |
| 30 | + var lastUsed: Long = System.currentTimeMillis() |
| 31 | + |
| 32 | + override fun compareTo(other: CacheItem): Int { |
| 33 | + return when { |
| 34 | + this.expiryTime != other.expiryTime -> this.expiryTime.compareTo(other.expiryTime) |
| 35 | + this.priority != other.priority -> this.priority.compareTo(other.priority) |
| 36 | + else -> this.lastUsed.compareTo(other.lastUsed) |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Returns fixed system time in milliseconds |
| 42 | + private fun getSystemTimeForExpiry() = 1000 |
| 43 | +} |
| 44 | + |
| 45 | +private class Test { |
| 46 | + @Test |
| 47 | + fun `add and get`() { |
| 48 | + val cache = AdvancedLRUCache(2) |
| 49 | + cache.put("A", 1, 5, 5000) |
| 50 | + |
| 51 | + cache.get("A") shouldBeEqualTo 1 |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + fun `evict by priority`() { |
| 56 | + val cache = AdvancedLRUCache(2) |
| 57 | + cache.put("A", 1, 1, 3000) |
| 58 | + cache.put("B", 2, 3, 4000) |
| 59 | + cache.put("C", 3, 4, 5000) |
| 60 | + |
| 61 | + // This should be null because "A" was evicted due to lower priority. |
| 62 | + cache.get("A") shouldBeEqualTo null |
| 63 | + cache.get("B") shouldBeEqualTo 2 |
| 64 | + cache.get("C") shouldBeEqualTo 3 |
| 65 | + } |
| 66 | + |
| 67 | + @Test |
| 68 | + fun `evict by expiry`() { |
| 69 | + val cache = AdvancedLRUCache(2) |
| 70 | + cache.put("A", 1, 1, 500) |
| 71 | + cache.put("B", 2, 3, 700) |
| 72 | + |
| 73 | + // This should be null because "A" was evicted due to expiry. |
| 74 | + cache.get("A") shouldBeEqualTo null |
| 75 | + cache.get("B") shouldBeEqualTo null |
| 76 | + } |
| 77 | +} |
0 commit comments