aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGioele Bucci <gioelebucci@gmail.com>2024-05-28 23:30:33 +0200
committerLouis Pilfold <louis@lpil.uk>2024-05-29 18:56:17 +0100
commit09e2c7ee3950b0fa22d9ca1b1b68d71cc811d018 (patch)
treec5338b342d810bf701b865d6a780f2766bc9cb87
parent4ff82ff41bef6f308ac66afe0ab3e5d27ba4f7b0 (diff)
downloadgleam_stdlib-09e2c7ee3950b0fa22d9ca1b1b68d71cc811d018.tar.gz
gleam_stdlib-09e2c7ee3950b0fa22d9ca1b1b68d71cc811d018.zip
Fix infinite recursion loop in `list.window` when `by` is 0
The function would enter an endless loop if 0 was passed as second argument, for e.g `list.window([1, 2], 0) // endless loop!`
-rw-r--r--src/gleam/list.gleam6
-rw-r--r--test/gleam/list_test.gleam4
2 files changed, 8 insertions, 2 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index e782b45..83870b4 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -1913,8 +1913,10 @@ fn do_window(acc: List(List(a)), l: List(a), n: Int) -> List(List(a)) {
/// ```
///
pub fn window(l: List(a), by n: Int) -> List(List(a)) {
- do_window([], l, n)
- |> reverse
+ case n <= 0 {
+ True -> []
+ False -> do_window([], l, n) |> reverse
+ }
}
/// Returns a list of tuples containing two contiguous elements.
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index 190a49b..d20f7a0 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -1074,6 +1074,10 @@ pub fn window_test() {
|> list.window(3)
|> should.equal([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ [1, 2, 3]
+ |> list.window(0)
+ |> should.equal([])
+
// TCO test
list.range(0, recursion_test_cycles)
|> list.window(2)