Skip to content

Commit

Permalink
prevent modification of original array with fromArray
Browse files Browse the repository at this point in the history
  • Loading branch information
andogq committed May 7, 2024
1 parent d443ab0 commit 01dff15
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/swift-years-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"windpipe": patch
---

clone array in `fromArray` to prevent mutating original array
6 changes: 6 additions & 0 deletions src/stream/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,17 @@ export class StreamBase {
/**
* Create a stream from an array.
*
* @note The array will be shallow cloned internally, so that the original array won't be
* impacted.
*
* @param array - The array that values will be emitted from.
*
* @group Creation
*/
static fromArray<T, E>(array: MaybeAtom<T, E>[]): Stream<T, E> {
// Clone the array so that shifting elements doesn't impact the original array.
array = [...array];

return Stream.fromNext(async () => {
return array.shift() ?? StreamBase.StreamEnd;
});
Expand Down
20 changes: 20 additions & 0 deletions test/creation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,26 @@ describe.concurrent("stream creation", () => {
});
});

describe.concurrent("from array", () => {
test("simple array", async ({ expect }) => {
expect.assertions(1);

const s = $.fromArray([1, 2, 3]);

expect(await s.toArray({ atoms: true })).toEqual([$.ok(1), $.ok(2), $.ok(3)]);
});

test("don't modify original array", async ({ expect }) => {
expect.assertions(2);

const array = [1, 2, 3];
const s = $.fromArray(array);

expect(await s.toArray({ atoms: true })).toEqual([$.ok(1), $.ok(2), $.ok(3)]);
expect(array).toHaveLength(3);
});
});

describe.concurrent("from callback", () => {
/**
* Sample function that accepts a node-style callback.
Expand Down

0 comments on commit 01dff15

Please sign in to comment.