diff --git a/builtin/builtin.mbti b/builtin/builtin.mbti index de7a0ff19..f613ceddd 100644 --- a/builtin/builtin.mbti +++ b/builtin/builtin.mbti @@ -209,6 +209,7 @@ impl Iter { head[A](Self[A]) -> A? intersperse[A](Self[A], A) -> Self[A] iter[T](Self[T]) -> Self[T] + join(Self[String], separator~ : String = ..) -> String just_run[T](Self[T], (T) -> IterResult) -> Unit last[A](Self[A]) -> A? map[T, R](Self[T], (T) -> R) -> Self[R] diff --git a/builtin/iter.mbt b/builtin/iter.mbt index 58d1c55b1..8cc01337f 100644 --- a/builtin/iter.mbt +++ b/builtin/iter.mbt @@ -781,6 +781,28 @@ pub fn collect[T](self : Iter[T]) -> Array[T] { result } +///| +/// Collects the elements of the iterator into a string. +pub fn join(self : Iter[String], separator~ : String = "") -> String { + let buf = StringBuilder::new() + if separator == "" { + for str in self { + buf.write_string(str) + } + } else { + let mut first = true + for str in self { + if first { + first = false + } else { + buf.write_string(separator) + } + buf.write_string(str) + } + } + buf.to_string() +} + ///| /// Iter itself is an iterator. /// so that it works with array spread operator. e.g, `[..iter]` diff --git a/builtin/iter_test.mbt b/builtin/iter_test.mbt index 17c1e1df0..e1d83b49c 100644 --- a/builtin/iter_test.mbt +++ b/builtin/iter_test.mbt @@ -551,3 +551,23 @@ test "peek function - random cases" { let iter5 = [0, 0, 0].iter() inspect!(iter5.peek(), content="Some(0)") } + +test "@builtin.join/empty_iter" { + let empty_iter : Iter[String] = Iter::empty() + inspect!(@builtin.join(empty_iter), content="") +} + +test "@builtin.join/single_element" { + let single_elem_iter : Iter[String] = Iter::singleton("Test") + inspect!(@builtin.join(single_elem_iter), content="Test") +} + +test "@builtin.join/multiple_elements_with_separator" { + let iter : Iter[String] = ["A", "B", "C"].iter() + inspect!(@builtin.join(iter, separator=","), content="A,B,C") +} + +test "@builtin.join/multiple_elements_without_separator" { + let iter : Iter[String] = ["A", "B", "C"].iter() + inspect!(@builtin.join(iter), content="ABC") +}