Skip to content

Commit

Permalink
Add iterate function
Browse files Browse the repository at this point in the history
  • Loading branch information
lunagl committed Dec 11, 2023
1 parent 291a794 commit a5d6650
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/glearray.gleam
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import gleam/iterator.{type Iterator}

pub type Array(a)

@external(erlang, "glearray_ffi", "new")
Expand Down Expand Up @@ -64,3 +66,11 @@ pub fn insert(
@external(erlang, "glearray_ffi", "insert")
@external(javascript, "./glearray_ffi.mjs", "insert")
fn do_insert(array: Array(a), index: Int, value: a) -> Array(a)

pub fn iterate(array: Array(a)) -> Iterator(a) {
use index <- iterator.unfold(from: 0)
case at(array, index) {
Ok(element) -> iterator.Next(element, index + 1)
Error(_) -> iterator.Done
}
}
15 changes: 15 additions & 0 deletions test/glearray_test.gleam
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import gleam/list
import gleam/function
import gleam/result
import gleam/iterator
import gleeunit
import gleeunit/should
import glearray.{type Array}
Expand Down Expand Up @@ -100,6 +101,20 @@ pub fn insert_test() {
|> should.equal(Ok([1, 2, 3, 20]))
}

pub fn iterate_test() {
iterate([])
iterate([1, 2, 3, 4])
iterate([0.4, 6.1, 99.9, -64.0])
}

fn iterate(list: List(a)) {
list
|> glearray.from_list
|> glearray.iterate
|> iterator.to_list
|> should.equal(list)
}

fn assert_empty(array: Array(a)) -> Array(a) {
assert_length(array, 0)
should.equal(array, glearray.new())
Expand Down

0 comments on commit a5d6650

Please sign in to comment.