From 500ec862a1572bdd93c216c63b1f43029e4c455f Mon Sep 17 00:00:00 2001 From: Artem Melnyk Date: Mon, 19 Feb 2024 20:02:17 +0100 Subject: [PATCH] fix(PageIterator): can't get the last element with collect method --- pagination.test.ts | 64 ++++++++++++++++++++++++++++++++++++++++++++++ pagination.ts | 8 +++--- 2 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 pagination.test.ts diff --git a/pagination.test.ts b/pagination.test.ts new file mode 100644 index 0000000..94b331d --- /dev/null +++ b/pagination.test.ts @@ -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); +}); diff --git a/pagination.ts b/pagination.ts index 0c45c1b..03e91e7 100644 --- a/pagination.ts +++ b/pagination.ts @@ -82,11 +82,11 @@ export class PageIterator { this.defaults = { ...DEFAULTS, ...defaults }; } - asyncIterator(): AsyncGenerator { + asyncIterator(): AsyncGenerator { return this[Symbol.asyncIterator](); } - async *[Symbol.asyncIterator](): AsyncGenerator { + async *[Symbol.asyncIterator](): AsyncGenerator { let { direction, limit, offset } = this.defaults; while (true) { @@ -96,10 +96,8 @@ export class PageIterator { (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;