Skip to content

Commit

Permalink
fix(PageIterator): can't get the last element with collect method
Browse files Browse the repository at this point in the history
  • Loading branch information
MellKam committed Feb 19, 2024
1 parent 59fbcea commit 500ec86
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 5 deletions.
64 changes: 64 additions & 0 deletions pagination.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { PageIterator } from "./pagination.ts";
import { assertEquals } from "std/assert/mod.ts";

type MockArtist = {
id: number;
type: "artist";
name: string;
};
const totalMockItems = 50;
const mockArtists: MockArtist[] = Array(totalMockItems).fill(0).map((
_,
i,
) => ({
id: i,
type: "artist",
name: "Radiohead",
}));

Deno.test("PageIterator: asyncIterator", async () => {
const pageIterator = new PageIterator((opts) => {
const limit = opts.limit || 20;
const offset = opts.offset || 0;

return Promise.resolve({
href: "#",
items: mockArtists.slice(offset, offset + limit),
offset,
limit,
next: offset + limit < totalMockItems ? "http://example.com" : null,
previous: offset > 0 ? "http://example.com" : null,
total: totalMockItems,
});
});

const iter = pageIterator.asyncIterator();

for (let i = 0; i < totalMockItems; i++) {
assertEquals(await iter.next(), { done: false, value: mockArtists[i] });
}
assertEquals(await iter.next(), {
done: true,
value: null,
});
});

Deno.test("PageIterator: collect", async () => {
const pageIterator = new PageIterator((opts) => {
const limit = opts.limit || 20;
const offset = opts.offset || 0;

return Promise.resolve({
href: "#",
items: mockArtists.slice(offset, offset + limit),
offset,
limit,
next: offset + limit < totalMockItems ? "http://example.com" : null,
previous: offset > 0 ? "http://example.com" : null,
total: totalMockItems,
});
});

const items = await pageIterator.collect();
assertEquals(items, mockArtists);
});
8 changes: 3 additions & 5 deletions pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ export class PageIterator<TItem> {
this.defaults = { ...DEFAULTS, ...defaults };
}

asyncIterator(): AsyncGenerator<TItem, TItem, unknown> {
asyncIterator(): AsyncGenerator<TItem, null, unknown> {
return this[Symbol.asyncIterator]();
}

async *[Symbol.asyncIterator](): AsyncGenerator<TItem, TItem> {
async *[Symbol.asyncIterator](): AsyncGenerator<TItem, null, unknown> {
let { direction, limit, offset } = this.defaults;

while (true) {
Expand All @@ -96,10 +96,8 @@ export class PageIterator<TItem> {
(direction === "next" && !chunk.next) ||
(direction === "prev" && !chunk.previous)
) {
const last = chunk.items.pop()!;
for (const item of chunk.items) yield item;

return last;
return null;
}

for (const item of chunk.items) yield item;
Expand Down

0 comments on commit 500ec86

Please sign in to comment.