aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Saxton <peterhsaxton@gmail.com>2020-06-06 13:09:43 +0100
committerLouis Pilfold <louis@lpil.uk>2020-06-07 20:36:07 +0100
commit3a981f8d584baa621e659f45f80654710daea2b1 (patch)
treeaf9fca6d05b4d1dee89e94aac3faf9d4d3cb91b8
parent17516f90eb47a8e78e0ffe1dc37eee363e8c58a0 (diff)
downloadgleam_stdlib-3a981f8d584baa621e659f45f80654710daea2b1.tar.gz
gleam_stdlib-3a981f8d584baa621e659f45f80654710daea2b1.zip
split_once function for strings
-rw-r--r--src/gleam/string.gleam25
-rw-r--r--test/gleam/string_test.gleam14
2 files changed, 38 insertions, 1 deletions
diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam
index 7c2f188..3c49c87 100644
--- a/src/gleam/string.gleam
+++ b/src/gleam/string.gleam
@@ -239,7 +239,7 @@ pub external fn ends_with(String, String) -> Bool =
/// ## Examples
///
/// > split("home/gleam/desktop/", on: "/")
-/// ["home","gleam","desktop", ""]
+/// ["home", "gleam", "desktop", ""]
///
pub fn split(x: String, on substring: String) -> List(String) {
x
@@ -248,6 +248,29 @@ pub fn split(x: String, on substring: String) -> List(String) {
|> list.map(with: iodata.to_string)
}
+external fn erl_split(String, String) -> List(String) =
+ "string" "split"
+
+/// Splits a string a single time on the given substring.
+///
+/// Returns an error if substring not present.
+///
+/// ## Examples
+///
+/// > split_once("home/gleam/desktop/", on: "/")
+/// Ok(tuple("home", "gleam/desktop/"))
+///
+/// > split_once("home/gleam/desktop/", on: "?")
+/// Error(Nil)
+///
+pub fn split_once(x: String, on substring: String) -> Result(tuple(String, String), Nil) {
+ case erl_split(x, substring) {
+ [first, rest] -> Ok(tuple(first, rest))
+ _ -> Error(Nil)
+ }
+}
+
+
/// Create a new string by joining two strings together.
///
/// This function copies both strings and runs in linear time. If you find
diff --git a/test/gleam/string_test.gleam b/test/gleam/string_test.gleam
index 2fbb84f..a9b0d79 100644
--- a/test/gleam/string_test.gleam
+++ b/test/gleam/string_test.gleam
@@ -38,6 +38,20 @@ pub fn split_test() {
|> should.equal(["Gleam", "Erlang,Elixir"])
}
+pub fn split_first_test() {
+ "Gleam,Erlang,Elixir"
+ |> string.split_once(",")
+ |> should.equal(Ok(tuple("Gleam", "Erlang,Elixir")))
+
+ "Gleam"
+ |> string.split_once(",")
+ |> should.equal(Error(Nil))
+
+ ""
+ |> string.split_once(",")
+ |> should.equal(Error(Nil))
+}
+
pub fn replace_test() {
"Gleam,Erlang,Elixir"
|> string.replace(",", "++")