fix(combinations-replacement): return an empty list for a non-positive group size

combinationsReplacement recurses on x.slice(i, x.length), which at i = 0 is
as long as the input, so the only exit left is the k === 1 base case. For
k <= 0 the counter starts below that case and moves away from it, and the
recursion overflows the stack. The sibling combinations recurses on
x.slice(i + 1, x.length), runs out of input and returns [] for the same
arguments.

Guard the non-positive group size up front so both functions agree.
This commit is contained in:
dualfroz committed 2026-09-03 14:04:54 +02:00
1 parent 1aa682fd34
commit 24fe35e78e
3 files changed
+38

No files matched your search

@@ -0,0 +1,5 @@
---
"simple-statistics": patch
---
Fix `combinationsReplacement` overflowing the stack for a non-positive group size. `combinations` recurses on `x.slice(i + 1, x.length)`, so it always runs out of input and returns `[]` for `k <= 0`. `combinationsReplacement` recurses on `x.slice(i, x.length)`, which at `i = 0` is as long as `x`, so with `k` counting down past its `k === 1` base case the recursion never terminates: `combinationsReplacement([1, 2, 3], 0)` and `combinationsReplacement([1, 2, 3], -1)` both threw `RangeError: Maximum call stack size exceeded`. Both now return `[]`, matching the sibling function.