Skip to content

Commit

Permalink
Merge pull request #51 from chickensoft-games/fix/map-readonly
Browse files Browse the repository at this point in the history
fix: implement read only dictionary from map
  • Loading branch information
jolexxa authored Oct 12, 2024
2 parents 75fe4e5 + 318efd4 commit b18f9e5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 14 additions & 0 deletions Chickensoft.Collections.Tests/src/MapTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,12 @@ public void KeysAreOrdered() {
["a"] = 1,
};

var readonlyMap = map as IReadOnlyDictionary<string, int>;

map["b"] = 3;

map.Keys.ShouldBe(["b", "a"]);
readonlyMap.Keys.ShouldBe(["b", "a"]);
}

[Fact]
Expand All @@ -170,12 +173,23 @@ public void Values() {
["a"] = 1,
["b"] = 2
};

var readonlyMap = map as IReadOnlyDictionary<string, int>;

var values = map.Values.ToList();

values.ShouldBeAssignableTo<ICollection<int>>();

values[0].ShouldBe(1);
values[1].ShouldBe(2);


values = readonlyMap.Values.ToList();

values.ShouldBeAssignableTo<ICollection<int>>();

values[0].ShouldBe(1);
values[1].ShouldBe(2);
}

[Fact]
Expand Down
12 changes: 11 additions & 1 deletion Chickensoft.Collections/src/collections/Map.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ namespace Chickensoft.Collections;
/// <typeparam name="TKey">Key type.</typeparam>
/// <typeparam name="TValue">Value type.</typeparam>
public class Map<TKey, TValue> :
IDictionary<TKey, TValue> where TKey : notnull {
IDictionary<TKey, TValue>,
IReadOnlyDictionary<TKey, TValue>
where TKey : notnull {

private readonly OrderedDictionary _collection = [];

Expand Down Expand Up @@ -71,6 +73,14 @@ public Map(IEnumerable<KeyValuePair<TKey, TValue>> collection) {
public ICollection<TValue> Values =>
_collection.Values.Cast<TValue>().ToArray();

#region IReadOnlyDictionary<TKey, TValue>
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys =>
_collection.Keys.Cast<TKey>();

IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values =>
_collection.Values.Cast<TValue>();
#endregion IReadOnlyDictionary<TKey, TValue>

/// <summary>Insert a key and value at the specified index.</summary>
/// <param name="index">Index to insert to.</param>
/// <param name="key">Key.</param>
Expand Down

0 comments on commit b18f9e5

Please sign in to comment.