From 4ad40c4789bcf4dea22e91a5289dd0aafd213b21 Mon Sep 17 00:00:00 2001 From: Mathias Jean Johansen Date: Sun, 1 May 2022 13:18:08 +0200 Subject: Add `last` function to `String`s. --- src/gleam/string.gleam | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src') diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam index ac7d3aa..3cec7d2 100644 --- a/src/gleam/string.gleam +++ b/src/gleam/string.gleam @@ -762,3 +762,26 @@ pub fn first(s: String) -> Option(String) { _ -> Some(slice(s, 0, 1)) } } + +/// 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)`. +/// +/// ## Examples +/// +/// ```gleam +/// > last("") +/// None +/// ``` +/// +/// ```gleam +/// > last("icecream") +/// Some("m") +/// ``` +/// +pub fn last(s: String) -> Option(String) { + case length(s) { + 0 -> None + _ -> Some(slice(s, length(s) - 1, 1)) + } +} -- cgit v1.2.3