Skip to content

Commit

Permalink
Add insert function
Browse files Browse the repository at this point in the history
  • Loading branch information
lunagl committed Dec 11, 2023
1 parent e1ef76d commit 291a794
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/glearray.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,19 @@ fn is_valid_index(array: Array(a), index: Int) -> Bool {

@external(erlang, "erlang", "append_element")
@external(javascript, "./glearray_ffi.mjs", "push")
pub fn push(to array: Array(a), value value: a) -> Array(a)
pub fn push(onto array: Array(a), value value: a) -> Array(a)

pub fn insert(
into array: Array(a),
at index: Int,
value value: a,
) -> Result(Array(a), Nil) {
case index >= 0 && index <= length(array) {
True -> Ok(do_insert(array, index, value))
False -> Error(Nil)
}
}

@external(erlang, "glearray_ffi", "insert")
@external(javascript, "./glearray_ffi.mjs", "insert")
fn do_insert(array: Array(a), index: Int, value: a) -> Array(a)
4 changes: 3 additions & 1 deletion src/glearray_ffi.erl
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
-module(glearray_ffi).

-export([new/0, at/2, set/3]).
-export([new/0, at/2, set/3, insert/3]).

new() -> {}.

at(Array, Index) -> element(Index + 1, Array).

set(Array, Index, Value) -> setelement(Index + 1, Array, Value).

insert(Array, Index, Value) -> erlang:insert_element(Index + 1, Array, Value).
4 changes: 4 additions & 0 deletions src/glearray_ffi.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ export function push(array, value) {
copy.push(value);
return copy;
}

export function insert(array, index, value) {
return array.toSpliced(index, 0, value);
}
17 changes: 17 additions & 0 deletions test/glearray_test.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import gleam/list
import gleam/function
import gleam/result
import gleeunit
import gleeunit/should
import glearray.{type Array}
Expand Down Expand Up @@ -83,6 +84,22 @@ pub fn push_test() {
|> should.equal([1, 2, 3])
}

pub fn insert_test() {
let array = glearray.from_list([1, 2, 3])
array
|> glearray.insert(at: 0, value: 9)
|> result.map(glearray.to_list)
|> should.equal(Ok([9, 1, 2, 3]))
array
|> glearray.insert(at: 2, value: -1)
|> result.map(glearray.to_list)
|> should.equal(Ok([1, 2, -1, 3]))
array
|> glearray.insert(3, 20)
|> result.map(glearray.to_list)
|> should.equal(Ok([1, 2, 3, 20]))
}

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

0 comments on commit 291a794

Please sign in to comment.