Skip to content

Commit

Permalink
Implement ImmArray.Find and ImmSet.TryGetValue.
Browse files Browse the repository at this point in the history
Closes #2.
  • Loading branch information
oconnor0 committed Oct 25, 2024
1 parent c19c74a commit 235281d
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Xledger.Collections.Test/TestImmArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ public void TestCompareToRecord() {
Assert.ThrowsAny<ArgumentException>(() => imm2 >= imm1);
}

[Fact]
public void TestFind() {
var arr = Enumerable.Range(-1, 100).ToArray();
var imm = arr.ToImmArray();

Predicate<int> pred = i => i == -1;
Assert.Equal(Array.Find(arr, pred), imm.Find(pred));
pred = i => i == 12;
Assert.Equal(Array.Find(arr, pred), imm.Find(pred));
pred = i => i == 75;
Assert.Equal(Array.Find(arr, pred), imm.Find(pred));
pred = i => i == 1_000_000;
Assert.Equal(Array.Find(arr, pred), imm.Find(pred));
}

public record Employee(int Id, string Name, decimal Salary);
}

19 changes: 19 additions & 0 deletions Xledger.Collections.Test/TestImmSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,25 @@ public void TestContains() {
Assert.True(lst.Contains(3));
}

[Fact]
public void TestTryGetValue() {
var imm = ImmSet.Of("foo", "bar", "baz");

var lookup = "food".Substring(0, 3);
var found = imm.TryGetValue(lookup, out var actual);
Assert.True(found);
Assert.NotSame(lookup, actual);
Assert.Equal(lookup, actual);

found = imm.TryGetValue("foo", out actual);
Assert.True(found);
Assert.Same("foo", actual);
Assert.Equal("foo", actual);

found = imm.TryGetValue("food", out actual);
Assert.False(found);
}

[Fact]
public void TestNoOps() {
var imm = ImmSet.Of(7, 6, 5, 4);
Expand Down
7 changes: 7 additions & 0 deletions Xledger.Collections/ImmArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,13 @@ public bool Contains(T item) {
return this.data.Length > 0 && IndexOf(item) >= 0;
}

/// <summary>
/// Returns the first matching element or default if none matches.
/// </summary>
public T Find(Predicate<T> pred) {
return Array.Find(this.data, pred);
}

/// <inheritdoc />
public int IndexOf(T item) {
return Array.IndexOf<T>(this.data, item);
Expand Down
7 changes: 7 additions & 0 deletions Xledger.Collections/ImmSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ public bool SetEquals(IEnumerable<T> other) {
}
}

/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
public bool TryGetValue(T equalValue, out T actualValue) {
return this.data.TryGetValue(equalValue, out actualValue);
}

/// <inheritdoc />
public override string ToString() {
return $"[{string.Join(", ", this.data)}]";
Expand Down

0 comments on commit 235281d

Please sign in to comment.