Skip to content

Commit 7fb502e

Browse files
committed
Feat: Dictionary GetOrAdd
1 parent 29ff97e commit 7fb502e

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/CodeOfChaos.Extensions/DictionaryExtensions.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,24 @@ TValue value
2727
return true;
2828

2929
}
30+
31+
public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory) where TKey : notnull {
32+
if (dictionary.TryGetValue(key, out TValue? value)) return value;
33+
value = valueFactory(key);
34+
dictionary.Add(key, value);
35+
return value;
36+
}
37+
38+
public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value) where TKey : notnull {
39+
if (dictionary.TryGetValue(key, out TValue? existingValue)) return existingValue;
40+
dictionary.Add(key, value);
41+
return value;
42+
}
43+
44+
public static TValue GetOrAdd<TKey, TValue, TArg>(this Dictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) where TKey : notnull {
45+
if (dictionary.TryGetValue(key, out TValue? value)) return value;
46+
value = valueFactory(key, factoryArgument);
47+
dictionary.Add(key, value);
48+
return value;
49+
}
3050
}

tests/Tests.CodeOfChaos.Extensions/DictionaryExtensionTests.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,36 @@ public async Task TryAddToOrCreateCollection_ShouldNotAddValue_WhenValueAlreadyE
7777
await Assert.That(result).IsFalse();
7878
await Assert.That(dictionary["key1"]).IsEquivalentTo(new List<int> { 1 });
7979
}
80+
81+
[Test]
82+
public async Task GetOrAdd_ShouldAddValueToDictionary_WhenKeyDoesNotExist() {
83+
// Arrange
84+
var dictionary = new Dictionary<string, string>();
85+
string value = "value";
86+
Func<string, string> valueFactory = (_) => value;
87+
88+
// Act
89+
var newValue = dictionary.GetOrAdd("key1", valueFactory);
90+
91+
// Assert
92+
await Assert.That(newValue).IsEqualTo(value);
93+
await Assert.That(dictionary.ContainsKey("key1")).IsTrue();
94+
await Assert.That(dictionary["key1"]).IsEqualTo(value);
95+
}
96+
97+
[Test]
98+
public async Task GetOrAdd_ShouldAddValueToDictionary_WhenKeyDoesNotExist_Overload() {
99+
// Arrange
100+
var dictionary = new Dictionary<string, string>();
101+
string value = "value";
102+
Func<string, int, string> valueFactory = (_, i) =>$"{value}{i}";
103+
104+
// Act
105+
string newValue = dictionary.GetOrAdd("key1", valueFactory, 10);
106+
107+
// Assert
108+
await Assert.That(newValue).IsEqualTo("value10");
109+
await Assert.That(dictionary.ContainsKey("key1")).IsTrue();
110+
await Assert.That(dictionary["key1"]).IsEqualTo("value10");
111+
}
80112
}

0 commit comments

Comments
 (0)