Skip to content

Commit

Permalink
add Option.equal (#615)
Browse files Browse the repository at this point in the history
@crusso 

I use this all the time when writing Matchers tests that require
equality checking. Would be nice to have in base 🙂
  • Loading branch information
ByronBecker authored Feb 12, 2024
1 parent 7939b37 commit c8245e4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Option.mo
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ module {
case _ { false }
};

/// Returns true if the optional arguments are equal according to the equality function provided, otherwise returns false.
public func equal<A>(x : ?A, y : ?A, eq : (A, A) -> Bool) : Bool = switch (x, y) {
case (null, null) { true };
case (?x_, ?y_) { eq(x_, y_) };
case (_, _) { false }
};

/// Asserts that the value is not `null`; fails otherwise.
/// @deprecated Option.assertSome will be removed soon; use an assert expression instead
public func assertSome(x : ?Any) = switch x {
Expand Down
12 changes: 12 additions & 0 deletions test/Option.test.mo
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Option "mo:base/Option";
import Int "mo:base/Int";
import Debug "mo:base/Debug";

Debug.print("Option");
Expand Down Expand Up @@ -263,4 +264,15 @@ do {
assert (false)
}
}
};

do {
Debug.print(" equal");

assert (Option.equal<Int>(null, null, Int.equal));
assert (Option.equal<Int>(?0, ?0, Int.equal));
assert (not Option.equal<Int>(?0, ?1, Int.equal));
assert (not Option.equal<Int>(?0, null, Int.equal));
assert (not Option.equal<Int>(null, ?0, Int.equal));
}

0 comments on commit c8245e4

Please sign in to comment.