Skip to content

Commit

Permalink
add Iter[String]::join
Browse files Browse the repository at this point in the history
  • Loading branch information
hackwaly committed Dec 9, 2024
1 parent 94ec402 commit 2dc847d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
22 changes: 22 additions & 0 deletions builtin/iter.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -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]`
Expand Down
20 changes: 20 additions & 0 deletions builtin/iter_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

0 comments on commit 2dc847d

Please sign in to comment.