Skip to content

Commit

Permalink
feat: last
Browse files Browse the repository at this point in the history
  • Loading branch information
ilteoood committed Nov 27, 2023
1 parent cc85726 commit e6eb5f4
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,20 @@ fromIterable(new Set([1, 2, 3]))
```
</details>
<details>
<summary>last</summary>
```javascript
import { last } from '@ilteoood/re-flusso/last';

const lastItemsToKeep = 3;

.pipeThrough(
last(lastItemsToKeep)
)
```
</details>
<details>
<summary>map</summary>
Expand Down
21 changes: 21 additions & 0 deletions src/last.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const last = <T>(lastItemsToKeep = 1): TransformStream<T> => {
const lastItems: T[] = [];

return new TransformStream<T, T>({
transform(chunk, controller) {
lastItems.push(chunk);

if (lastItems.length > lastItemsToKeep) {
lastItems.splice(0, 1);
}
},

flush(controller) {
const itemsLength = lastItems.length;

for (let i = 0; i < itemsLength; i++) {
controller.enqueue(lastItems[i]);
}
},
});
};
72 changes: 72 additions & 0 deletions test/last.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, expect, test } from "vitest";
import { fromIterable } from "../src/fromIterable";
import { last } from "../src/last";
import { pipeline } from "../src/pipeline";
import { toArray } from "../src/toArray";

describe("last", () => {
test("should keep last 2 items", async () => {
const sourceArray = [1, 2, 3];
const destinationArray = [];

await pipeline(
fromIterable(sourceArray),
last(2),
toArray(destinationArray),
);

expect(destinationArray).toEqual([2, 3]);
});

test("should keep items even if parameter greater than number of items", async () => {
const sourceArray = [1, 2, 3];
const destinationArray = [];

await pipeline(
fromIterable(sourceArray),
last(4),
toArray(destinationArray),
);

expect(destinationArray).toEqual([1, 2, 3]);
});

test("should not break for an empty array", async () => {
const sourceArray = [];
const destinationArray = [];

await pipeline(
fromIterable(sourceArray),
last(1),
toArray(destinationArray),
)

expect(destinationArray).toEqual(sourceArray);
})

test("should work even if parameter is not defined", async () => {
const sourceArray = [1, 2, 3];
const destinationArray = [];

await pipeline(
fromIterable(sourceArray),
last(),
toArray(destinationArray),
)

expect(destinationArray).toEqual([3]);
})

test("should skip everything if parameter is negative", async () => {
const sourceArray = [1, 2, 3];
const destinationArray = [];

await pipeline(
fromIterable(sourceArray),
last(-1),
toArray(destinationArray),
)

expect(destinationArray).toEqual([]);
})
});

0 comments on commit e6eb5f4

Please sign in to comment.