Skip to content

Commit 458cede

Browse files
committed
Refactor AddOrUpdate method to accept separate factory functions for adding and updating items in cache
1 parent 502aaed commit 458cede

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

FastCache/FastCache.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,13 +125,14 @@ public void AddOrUpdate(TKey key, TValue value, TimeSpan ttl)
125125
/// Factory pattern overload. Adds an item to cache if it does not exist, updates the existing item otherwise. Updating an item resets its TTL, essentially "sliding expiration".
126126
/// </summary>
127127
/// <param name="key">The key to add or update</param>
128-
/// <param name="valueFactory">The factory function used to generate the item for the key</param>
128+
/// <param name="addValueFactory">The factory function used to generate the item for the key</param>
129+
/// <param name="updateValueFactory">The factory function used to update the item for the key</param>
129130
/// <param name="ttl">TTL of the item</param>
130-
public void AddOrUpdate(TKey key, Func<TValue> valueFactory, TimeSpan ttl)
131+
public void AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory, TimeSpan ttl)
131132
{
132133
_dict.AddOrUpdate(key,
133-
addValueFactory: _ => new TtlValue(valueFactory(), ttl),
134-
updateValueFactory: (_, _) => new TtlValue(valueFactory(), ttl));
134+
addValueFactory: k => new TtlValue(addValueFactory(k), ttl),
135+
updateValueFactory: (k, v) => new TtlValue(updateValueFactory(k, v.Value), ttl));
135136
}
136137

137138
/// <summary>

UnitTests/UnitTests2.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ public void AddOrUpdate_WithFactory()
234234
int callCount = 0;
235235

236236
// Act
237-
cache.AddOrUpdate("key1", () => { callCount++; return 42; }, TimeSpan.FromMinutes(1));
237+
cache.AddOrUpdate("key1", _ => { callCount++; return 42; }, (_, _) => { callCount++; return 43; }, TimeSpan.FromMinutes(1));
238238
bool exists = cache.TryGet("key1", out int value);
239239

240240
// Assert
@@ -243,10 +243,10 @@ public void AddOrUpdate_WithFactory()
243243
Assert.AreEqual(1, callCount); // Factory should be called exactly once
244244

245245
callCount = 0;
246-
cache.AddOrUpdate("key1", () => { callCount++; return 43; }, TimeSpan.FromMinutes(1));
246+
cache.AddOrUpdate("key1", _ => { callCount++; return 44; }, (_, _) => { callCount++; return 45; }, TimeSpan.FromMinutes(1));
247247
exists = cache.TryGet("key1", out value);
248248
Assert.IsTrue(exists);
249-
Assert.AreEqual(43, value);
249+
Assert.AreEqual(45, value);
250250
Assert.AreEqual(1, callCount); // Factory should be called exactly once
251251
}
252252
}

0 commit comments

Comments
 (0)