Skip to content

Commit

Permalink
frontend: Add join() methods to Array and Vec
Browse files Browse the repository at this point in the history
  • Loading branch information
dinfuehr committed Dec 27, 2024
1 parent 7012521 commit 4eba95d
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
30 changes: 30 additions & 0 deletions pkgs/std/collections.dora
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ impl[T: Zero] Array[T] {
}
}

impl[T: Stringable] Array[T] {
pub fn join(separator: String): String {
let output = StringBuffer::new();

for (idx, element) in self.enumerate() {
if idx > 0 {
output.append(separator);
}

output.append(element.toString());
}

output.toString()
}
}

impl[T] IntoIterator for Array[T] {
type IteratorType = ArrayIter[T];

Expand Down Expand Up @@ -1407,6 +1423,20 @@ impl[T: Stringable] Vec[T] {
sb.append(")");
return sb.toString();
}

pub fn join(separator: String): String {
let output = StringBuffer::new();

for (idx, element) in self.enumerate() {
if idx > 0 {
output.append(separator);
}

output.append(element.toString());
}

output.toString()
}
}

impl[T1: Equals, T2: Equals] Equals for (T1, T2) {
Expand Down
13 changes: 13 additions & 0 deletions tests/stdlib/array-join1.dora
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
let x = Array[Int64]::new(1, 2, 3);
assert(x.join(", ") == "1, 2, 3");
assert(x.join("-") == "1-2-3");

let x = Array[Char]::new('a', 'b', 'c');
assert(x.join(", ") == "a, b, c");
assert(x.join("-") == "a-b-c");

let x = Array[Int64]::new(101, 102, 103);
assert(x.join(", ") == "101, 102, 103");
assert(x.join("-") == "101-102-103");
}
13 changes: 13 additions & 0 deletions tests/stdlib/vec-join1.dora
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
let x = Vec[Int64]::new(1, 2, 3);
assert(x.join(", ") == "1, 2, 3");
assert(x.join("-") == "1-2-3");

let x = Vec[Char]::new('a', 'b', 'c');
assert(x.join(", ") == "a, b, c");
assert(x.join("-") == "a-b-c");

let x = Vec[Int64]::new(101, 102, 103);
assert(x.join(", ") == "101, 102, 103");
assert(x.join("-") == "101-102-103");
}

0 comments on commit 4eba95d

Please sign in to comment.