Add Array.join for joining Array values

The method Array.join can be used to join values in an Array together
using a separator. This method is only available if the values in an
Array implement the ToString trait.
parent a64f2e70
Pipeline #99360813 passed with stages
in 13 minutes and 33 seconds
......@@ -13,7 +13,6 @@
# indexes, in which case the value will be accessed starting at the back of the
# Array. This means that -1 will access the last value, -2 the value before
# that, etc.
import std::conversion::ToArray
import std::index::(Index, SetIndex)
import std::length::Length
......
......@@ -4,8 +4,10 @@
# These types and methods are defined separately as otherwise `std::iterator`
# would depend on `std::array` while `std::array` would depend on
# `std::iterator`.
import std::conversion::ToString
import std::format::(self, Formatter, Inspect)
import std::iterator::(self, Iterator)
import std::string_buffer::StringBuffer
impl Array!(T) {
# Returns an `Iterator` that iterates over all values in `self`.
......@@ -26,6 +28,31 @@ impl Array!(T) {
self[index]
}
}
# Joins the values of `self` together using the separator.
#
# # Examples
#
# Joining an empty `Array`:
#
# Array.new.join(',') # => ''
#
# Joining an `Array` with multiple values:
#
# Array.new(10, 20, 30).join(',') # => '10,20,30'
def join(separator: String) -> String where T: ToString {
let buffer = StringBuffer.new
each_with_index do (value, index) {
index.positive?.if_true {
buffer.push(separator)
}
buffer.push(value.to_string)
}
buffer.to_string
}
}
impl Inspect for Array!(T) {
......
......@@ -228,3 +228,25 @@ test.group('std::array::Array.inspect') do (g) {
assert.equal(Array.new(10, 20).inspect, 'Array { 10, 20 }')
}
}
test.group('std::array::Array.join') do (g) {
g.test('Joining values in an empty Array') {
assert.equal(Array.new.join(','), '')
}
g.test('Joining a single value') {
assert.equal(Array.new(10).join(','), '10')
}
g.test('Joining multiple values') {
assert.equal(Array.new(10, 20, 30).join(','), '10,20,30')
}
g.test('Joining multiple values using multiple characters as the separator') {
assert.equal(Array.new(10, 20, 30).join('::'), '10::20::30')
}
g.test('Joining multiple values using an empty separator') {
assert.equal(Array.new(10, 20, 30).join(''), '102030')
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment