diff --git a/README.md b/README.md index f40a8b0..0552520 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,21 @@ const errorToThrow = new Error('Stream is empty'); ``` +
+numbers + +
+    fromRange + +```javascript +import { fromRange } from '@ilteoood/re-flusso/numbers/fromRange'; + +fromRange(1, 3) +``` +
+
+ +
pipeline diff --git a/src/numbers/fromRange.ts b/src/numbers/fromRange.ts new file mode 100644 index 0000000..f57f5f3 --- /dev/null +++ b/src/numbers/fromRange.ts @@ -0,0 +1,20 @@ +export const fromRange = ( + min: number, + max: number, + strategy?: QueuingStrategy, +): ReadableStream => { + let currentValue = min; + return new ReadableStream( + { + pull(controller) { + if (currentValue <= max) { + controller.enqueue(currentValue); + currentValue++; + } else { + controller.close(); + } + }, + }, + strategy, + ); +}; diff --git a/test/numbers/fromRange.test.ts b/test/numbers/fromRange.test.ts new file mode 100644 index 0000000..13066a5 --- /dev/null +++ b/test/numbers/fromRange.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, test } from "vitest"; +import { fromRange } from "../../src/numbers/fromRange"; +import { pipeline } from "../../src/pipeline"; +import { toArray } from "../../src/toArray"; + +describe("fromRange", () => { + test("should generate range", async () => { + const destinationArray = []; + + await pipeline(fromRange(1, 3), toArray(destinationArray)); + + expect(destinationArray).toEqual([1, 2, 3]); + }); + + test("should generate empty range when min > max", async () => { + const destinationArray = []; + + await pipeline(fromRange(3, 1), toArray(destinationArray)); + + expect(destinationArray).toEqual([]); + }); +});