From 761585957f887cc0fc3a9f8984e791fbc053e654 Mon Sep 17 00:00:00 2001 From: vmladenov Date: Sun, 2 Nov 2025 18:38:19 +0100 Subject: [PATCH] feat: enhance flat to support recursive flattening with depth -1 --- src/iterables/select-many.ts | 2 +- test/unit/select-many.spec.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/iterables/select-many.ts b/src/iterables/select-many.ts index d58dd2d..896adb6 100644 --- a/src/iterables/select-many.ts +++ b/src/iterables/select-many.ts @@ -29,7 +29,7 @@ export function flatMapIterator(input: Iterable, mapper export function* flatGenerator(input: Iterable, depth: number, level: number): Generator { for (const item of input) { if (Array.isArray(item)) { - if (level >= depth) { + if (depth > 0 && level >= depth) { yield item; } else { level++; diff --git a/test/unit/select-many.spec.ts b/test/unit/select-many.spec.ts index 243881f..7407e4e 100644 --- a/test/unit/select-many.spec.ts +++ b/test/unit/select-many.spec.ts @@ -110,6 +110,15 @@ describe('select many tests', () => { expect(output).toStrictEqual([1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e']); }); + it('should flat sequence recursive: depth -1', () => { + const input = [ + [1, 2, 3, 4, [5, 6, [7, [8, [9, [10, 11, [12]]]]]]], + 'e' + ]; + const output = from(input).flat(-1).toArray(); + expect(output).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 'e']); + }); + it('should flatMap sequence', () => { const input = [ [1, 2, 3, 4, [5, 6]],