aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMathias Jean Johansen <mathias@mjj.io>2022-05-02 18:02:34 +0200
committerLouis Pilfold <louis@lpil.uk>2022-05-04 22:08:15 +0100
commit267c3b8d2ff3340c022330dfb367128cddb69b51 (patch)
tree4a6a772e6b1565a3d4fb1d2b7a2db04d005699a7
parent0f9e6e6306290400ea031db921fad4dd68ba3564 (diff)
downloadgleam_stdlib-267c3b8d2ff3340c022330dfb367128cddb69b51.tar.gz
gleam_stdlib-267c3b8d2ff3340c022330dfb367128cddb69b51.zip
Refactor `last` to return a `Result`.
-rw-r--r--src/gleam/string.gleam18
-rw-r--r--test/gleam/string_test.gleam8
2 files changed, 13 insertions, 13 deletions
diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam
index 89cdc6c..bc13758 100644
--- a/src/gleam/string.gleam
+++ b/src/gleam/string.gleam
@@ -763,26 +763,26 @@ pub fn first(s: String) -> Result(String, Nil) {
}
}
-/// Returns the last element in a grapheme and wraps it in an `Option(String)`.
-/// If the `String` is empty, it returns `None`. Otherwise, it returns
-/// `Some(String)`.
+/// Returns the last grapheme cluster in a given `String` and wraps it in a
+/// `Result(String, Nil)`. If the `String` is empty, it returns `Error(Nil)`.
+/// Otherwise, it returns `Ok(String)`.
///
/// ## Examples
///
/// ```gleam
/// > last("")
-/// None
+/// Error(Nil)
/// ```
///
/// ```gleam
/// > last("icecream")
-/// Some("m")
+/// Ok("m")
/// ```
///
-pub fn last(s: String) -> Option(String) {
- case length(s) {
- 0 -> None
- _ -> Some(slice(s, -1, 1))
+pub fn last(s: String) -> Result(String, Nil) {
+ case pop_grapheme(s) {
+ Ok(#(_, rest)) -> Ok(slice(rest, -1, 1))
+ Error(e) -> Error(e)
}
}
diff --git a/test/gleam/string_test.gleam b/test/gleam/string_test.gleam
index 56b50a0..d6e1c23 100644
--- a/test/gleam/string_test.gleam
+++ b/test/gleam/string_test.gleam
@@ -382,19 +382,19 @@ pub fn first_test() {
pub fn last_test() {
""
|> string.last
- |> should.equal(None)
+ |> should.be_error
"gleam"
|> string.last
- |> should.equal(Some("m"))
+ |> should.equal(Ok("m"))
"gleam "
|> string.last
- |> should.equal(Some(" "))
+ |> should.equal(Ok(" "))
"եոգլի"
|> string.last
- |> should.equal(Some("ի"))
+ |> should.equal(Ok("ի"))
}
pub fn capitalize_test() {