Skip to content

Commit

Permalink
feat: add a way to execute a function on each page of a listing
Browse files Browse the repository at this point in the history
  • Loading branch information
thislooksfun committed Mar 26, 2021
1 parent 11cde28 commit 313c4af
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions src/listings/listing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export default class Listing<T> {
}

/**
* Execute a function on each element of the listing.
* Execute a function on pages of the listing.
*
* If the function returns or resolves to `false`, the execution will be
* halted prematurely to allow breaking out in the middle of the iteration.
Expand All @@ -123,15 +123,13 @@ export default class Listing<T> {
*
* @returns A promise that resolves when the listing has been exausted.
*/
async each(fn: Awaitable<T, boolean | void>): Promise<void> {
async eachPage(fn: Awaitable<T[], boolean | void>): Promise<void> {
let page: Listing<T> | null = this;

do {
for (const el of page.arr) {
// If the function returns false at any point, we are done.
const res = await fn(el);
if (res === false) return;
}
// If the function returns false at any point, we are done.
const res = await fn(page.arr);
if (res === false) return;

if (page.next) {
page = page.next;
Expand All @@ -142,4 +140,25 @@ export default class Listing<T> {
}
} while (page != null);
}

/**
* Execute a function on each element of the listing.
*
* If the function returns or resolves to `false`, the execution will be
* halted prematurely to allow breaking out in the middle of the iteration.
*
* @param fn The function to execute.
*
* @returns A promise that resolves when the listing has been exausted.
*/
async each(fn: Awaitable<T, boolean | void>): Promise<void> {
await this.eachPage(async page => {
for (const el of page) {
// If the function returns false at any point, we are done.
const res = await fn(el);
if (res === false) return false;
}
return true;
});
}
}

0 comments on commit 313c4af

Please sign in to comment.