Skip to content

Commit

Permalink
perf: cache the lookahead for future use
Browse files Browse the repository at this point in the history
This commit does two things:

1. It speeds up repeated calls to `Listing.empty()` and calls to
   `Listing.each()` after a call to `Listing.empty()`
2. It fixes a potential out-of-memory issue when calling `empty()`.
   Previously it would recursivly call `empty()` on the next
   fetched page which could, in theory, result in another fetch.
  • Loading branch information
thislooksfun committed Mar 12, 2021
1 parent 3c25988 commit 4a6b8cb
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/listings/listing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export default class Listing<T> {
protected ctx: Context;
protected arr: T[];
protected more?: More<T>;
protected next?: Listing<T>;

/**
* Create a new listing.
Expand All @@ -66,12 +67,15 @@ export default class Listing<T> {
// If we have elements on hand, it's not empty.
if (this.arr.length > 0) return false;

// If arr is empty and we don't have a way to get more, we're empty.
// If arr is empty with no way to get more, it's empty.
if (!this.more) return true;

// TODO: Cache this somehow?
const list = await this.more.fetch(this.ctx);
return list.empty();
// This listing is empty but can fetch more. Do so, and if it was
// successful, it's not empty.
if (!this.next) {
this.next = await this.more.fetch(this.ctx);
}
return this.next.arr.length > 0;
}

/**
Expand Down Expand Up @@ -103,7 +107,9 @@ export default class Listing<T> {
if (res === false) return;
}

if (page.more) {
if (page.next) {
page = page.next;
} else if (page.more) {
page = await page.more.fetch(this.ctx);
} else {
page = null;
Expand Down

0 comments on commit 4a6b8cb

Please sign in to comment.