diff options
author | Louis Pilfold <louis@lpil.uk> | 2021-08-23 16:01:48 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-08-23 16:01:48 +0100 |
commit | a5ca2d8bdefb677c4c4dfac2bfe58149ff195a7e (patch) | |
tree | f701ed0c20006a16675625db36cbea4c76c5d843 | |
parent | 89c5655794e04aae3488d022185250e2ffd1d06c (diff) | |
download | gleam_stdlib-a5ca2d8bdefb677c4c4dfac2bfe58149ff195a7e.tar.gz gleam_stdlib-a5ca2d8bdefb677c4c4dfac2bfe58149ff195a7e.zip |
string.to_option
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | src/gleam/string.gleam | 22 | ||||
-rw-r--r-- | test/gleam/string_test.gleam | 11 |
3 files changed, 34 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index e52fce4..a04e070 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ JavaScript. - The `dynamic` module functions now return structured error values instead of a string error description. +- The `string` module gains the `to_option` function. ## v0.16.0 - 2021-06-17 diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam index 545d1e4..3f0ebe5 100644 --- a/src/gleam/string.gleam +++ b/src/gleam/string.gleam @@ -6,6 +6,7 @@ import gleam/iterator.{Iterator} import gleam/list import gleam/order import gleam/result +import gleam/option.{None, Option, Some} if erlang { import gleam/dynamic.{Dynamic} @@ -664,3 +665,24 @@ pub fn utf_codepoint(value: Int) -> Result(UtfCodepoint, Nil) { i -> Ok(unsafe_int_to_utf_codepoint(i)) } } + +/// Convert a string into an optional string where an empty string becomes `None`. +/// +/// ## Examples +/// +/// ```gleam +/// > to_option("") +/// None +/// ``` +/// +/// ```gleam +/// > to_option("") +/// None +/// ``` +/// +pub fn to_option(s: String) -> Option(String) { + case s { + "" -> None + _ -> Some(s) + } +} diff --git a/test/gleam/string_test.gleam b/test/gleam/string_test.gleam index 3612dbb..d3a8496 100644 --- a/test/gleam/string_test.gleam +++ b/test/gleam/string_test.gleam @@ -1,6 +1,7 @@ import gleam/string import gleam/should import gleam/order +import gleam/option.{None, Some} import gleam/io import gleam/bit_string @@ -355,3 +356,13 @@ pub fn bit_string_utf_codepoint_test() { assert Ok(snake) = string.utf_codepoint(128013) should.equal(<<snake:utf8_codepoint>>, <<"🐍":utf8>>) } + +pub fn to_option_test() { + "" + |> string.to_option + |> should.equal(None) + + "ok" + |> string.to_option + |> should.equal(Some("ok")) +} |