aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2023-01-21 12:26:14 +0000
committerLouis Pilfold <louis@lpil.uk>2023-02-26 18:51:30 +0000
commit6bb693f1af14a3ddbc3fd28468e07197e46cbaa9 (patch)
tree8148b45a13a1c1e1d21e8d6e6de0b286746c2514
parent2ac7dddf43a5bc814b3906234624d4d236271347 (diff)
downloadgleam_stdlib-6bb693f1af14a3ddbc3fd28468e07197e46cbaa9.tar.gz
gleam_stdlib-6bb693f1af14a3ddbc3fd28468e07197e46cbaa9.zip
bool.guard
-rw-r--r--src/gleam/bool.gleam33
-rw-r--r--test/gleam/bool_test.gleam14
2 files changed, 47 insertions, 0 deletions
diff --git a/src/gleam/bool.gleam b/src/gleam/bool.gleam
index e67fe66..c64ee97 100644
--- a/src/gleam/bool.gleam
+++ b/src/gleam/bool.gleam
@@ -323,3 +323,36 @@ pub fn to_string(bool: Bool) -> String {
True -> "True"
}
}
+
+/// Run a callback function if the given bool is `True`, otherwise return a
+/// default value.
+///
+/// This function is suitable for `use` expressions.
+///
+/// ## Examples
+///
+/// ```gleam
+/// > let name = "Kamaka"
+/// > use <- guard(name != "", or: "friend")
+/// > "Hello, " <> name
+/// "Hello, Kamaka"
+/// ```
+///
+/// ```gleam
+/// > let name = ""
+/// > use <- guard(name != "", or: "friend")
+/// > "Hello, " <> name
+/// "Hello, friend"
+/// ```
+///
+///
+pub fn guard(
+ requirement: Bool,
+ or alternative: t,
+ then consequence: fn() -> t,
+) -> t {
+ case requirement {
+ True -> consequence()
+ False -> alternative
+ }
+}
diff --git a/test/gleam/bool_test.gleam b/test/gleam/bool_test.gleam
index a362186..ab9e2de 100644
--- a/test/gleam/bool_test.gleam
+++ b/test/gleam/bool_test.gleam
@@ -155,3 +155,17 @@ pub fn to_string_test() {
bool.to_string(False)
|> should.equal("False")
}
+
+pub fn guard_test() {
+ assert 1 = {
+ let x = 1
+ use <- bool.guard(True, or: 2)
+ x
+ }
+
+ assert 2 = {
+ let x = 1
+ use <- bool.guard(False, or: 2)
+ x
+ }
+}