From 0a1994974bc9d1af62bb1f45797e6bba424138ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lazar=20Ljubenovi=C4=87?= Date: Fri, 3 Nov 2023 14:59:10 +0100 Subject: [PATCH] feat(operators/chunk): improve types When the `chunkSize` value is known at compile-time, the return type of the operator will now reflect that and return a suitable union of tuples instead of an array with a generic length. For example, `chunk(3)` will now return `Operator` instead of `Operator>`. Closes #13 --- src/operators/chunk.ts | 13 ++++++++++++- tests/operators.spec.ts | 10 ++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/operators/chunk.ts b/src/operators/chunk.ts index 2cbacc0..a27486a 100644 --- a/src/operators/chunk.ts +++ b/src/operators/chunk.ts @@ -40,13 +40,24 @@ import { Operator } from '../core/types' * ) * // => [[1, 2], [3, 4], [5]] */ +export function chunk (chunkSize: 1): Operator +export function chunk (chunkSize: 2): Operator +export function chunk (chunkSize: 3): Operator +export function chunk (chunkSize: 4): Operator +export function chunk (chunkSize: 5): Operator +export function chunk (chunkSize: 6): Operator +export function chunk (chunkSize: 7): Operator +export function chunk (chunkSize: 8): Operator +export function chunk (chunkSize: 9): Operator +export function chunk (chunkSize: 10): Operator +export function chunk (chunkSize: number): Operator> export function chunk (chunkSize: number): Operator> { if (!Number.isInteger(chunkSize) || chunkSize < 1) { throw new RangeError(`Chunk size must be an integer not less than 1; an attempt was made to define the chunk size as ${chunkSize}.`) } - return function *(iterable: Iterable): IterableIterator> { + return function* (iterable: Iterable): IterableIterator> { const buffer: Array = [] let count: number = 0 for (const item of iterable) { diff --git a/tests/operators.spec.ts b/tests/operators.spec.ts index 7589140..d90b0dd 100644 --- a/tests/operators.spec.ts +++ b/tests/operators.spec.ts @@ -101,6 +101,16 @@ describe(`Operators`, () => { chai.assert.throws(() => j.chunk(-1), RangeError) }) + it(`infers the correct type for chunk size 1`, () => { + const result = j.pipe([1, 2, 3], j.chunk(1)) + type Test = AssertTrue>> + }) + + it(`infers the correct type for chunk size 2`, () => { + const result = j.pipe([1, 2, 3], j.chunk(2)) + type Test = AssertTrue>> + }) + it(`@example 1`, () => { const actual = j.pipe( [1, 2, 3, 4],