Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Iter[String]::join #1301

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
@@ -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]
8 changes: 8 additions & 0 deletions builtin/iter.mbt
Original file line number Diff line number Diff line change
@@ -781,6 +781,14 @@ 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 {
Copy link
Contributor Author

@hackwaly hackwaly Dec 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we change the label "separator" to "sep"?

let buf = StringBuilder::new()
hackwaly marked this conversation as resolved.
Show resolved Hide resolved
(buf : Logger).write_iter(self, prefix="", suffix="", sep=separator)
buf.to_string()
}

///|
/// Iter itself is an iterator.
/// so that it works with array spread operator. e.g, `[..iter]`
20 changes: 20 additions & 0 deletions builtin/iter_test.mbt
Original file line number Diff line number Diff line change
@@ -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")
}
Loading