diff options
-rw-r--r-- | src/gleam/list.gleam | 59 | ||||
-rw-r--r-- | test/gleam/list_test.gleam | 19 |
2 files changed, 37 insertions, 41 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 414f64e..fdf2caf 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1377,41 +1377,40 @@ pub fn take_while( do_take_while(list, predicate, []) } -if erlang { - // TODO: JavaScript fix - fn do_chunk( - list: List(a), - f: fn(a) -> key, - previous_key: key, - current_chunk: List(a), - acc: List(List(a)), - ) -> List(List(a)) { - case list { - [] -> reverse([reverse(current_chunk), ..acc]) - [head, ..tail] -> { - let key = f(head) - case key == previous_key { - False -> - do_chunk(tail, f, key, [head], [reverse(current_chunk), ..acc]) - True -> do_chunk(tail, f, key, [head, ..current_chunk], acc) +fn do_chunk( + list: List(a), + f: fn(a) -> key, + previous_key: key, + current_chunk: List(a), + acc: List(List(a)), +) -> List(List(a)) { + case list { + [head, ..tail] -> { + let key = f(head) + case key == previous_key { + False -> { + let new_acc = [reverse(current_chunk), ..acc] + do_chunk(tail, f, key, [head], new_acc) } + _true -> do_chunk(tail, f, key, [head, ..current_chunk], acc) } } + _empty -> reverse([reverse(current_chunk), ..acc]) } +} - /// Returns a list of chunks in which - /// the result of calling `f` on each element is the same. - /// - /// ## Examples - /// - /// > [1, 2, 2, 3, 4, 4, 6, 7, 7] |> chunk(by: fn(n) { n % 2 }) - /// [[1], [2, 2], [3], [4, 4, 6], [7, 7]] - /// - pub fn chunk(in list: List(a), by f: fn(a) -> key) -> List(List(a)) { - case list { - [] -> [] - [head, ..tail] -> do_chunk(tail, f, f(head), [head], []) - } +/// Returns a list of chunks in which +/// the result of calling `f` on each element is the same. +/// +/// ## Examples +/// +/// > [1, 2, 2, 3, 4, 4, 6, 7, 7] |> chunk(by: fn(n) { n % 2 }) +/// [[1], [2, 2], [3], [4, 4, 6], [7, 7]] +/// +pub fn chunk(in list: List(a), by f: fn(a) -> key) -> List(List(a)) { + case list { + [] -> [] + [head, ..tail] -> do_chunk(tail, f, f(head), [head], []) } } diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam index 4c45d6e..62a99aa 100644 --- a/test/gleam/list_test.gleam +++ b/test/gleam/list_test.gleam @@ -640,17 +640,14 @@ pub fn take_while_test() { |> should.equal([1, 2]) } -if erlang { - // TODO: JavaScript fix - pub fn chunk_test() { - [1, 2, 3] - |> list.chunk(by: fn(n) { n % 2 }) - |> should.equal([[1], [2], [3]]) - - [1, 2, 2, 3, 4, 4, 6, 7, 7] - |> list.chunk(by: fn(n) { n % 2 }) - |> should.equal([[1], [2, 2], [3], [4, 4, 6], [7, 7]]) - } +pub fn chunk_test() { + [1, 2, 3] + |> list.chunk(by: fn(n) { n % 2 }) + |> should.equal([[1], [2], [3]]) + + [1, 2, 2, 3, 4, 4, 6, 7, 7] + |> list.chunk(by: fn(n) { n % 2 }) + |> should.equal([[1], [2, 2], [3], [4, 4, 6], [7, 7]]) } pub fn sized_chunk_test() { |