From 1272d312d9e827b999e28f05c8c549bf3d4dc8ee Mon Sep 17 00:00:00 2001 From: buttercat1791 Date: Fri, 28 Mar 2025 23:30:11 -0500 Subject: [PATCH] Support async find for lazy publication tree nodes --- src/lib/data_structures/publication_tree.ts | 14 +++++++-- src/lib/utils.ts | 35 +++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/lib/data_structures/publication_tree.ts b/src/lib/data_structures/publication_tree.ts index 9c5cb64..e273711 100644 --- a/src/lib/data_structures/publication_tree.ts +++ b/src/lib/data_structures/publication_tree.ts @@ -205,11 +205,19 @@ export class PublicationTree implements AsyncIterable { const parent = this.target.parent; const siblings = parent?.children; - const currentIndex = siblings?.findIndex(async sibling => - (await sibling.value()).address === this.target!.address + if (!siblings) { + return false; + } + + const currentIndex = await siblings.findIndexAsync( + async (sibling: Lazy) => (await sibling.value()).address === this.target!.address ); - const nextSibling = (await siblings?.at(currentIndex! + 1)?.value()) ?? null; + if (currentIndex === -1) { + return false; + } + + const nextSibling = (await siblings.at(currentIndex + 1)?.value()) ?? null; if (!nextSibling) { return false; } diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 3a54d64..021c979 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -109,3 +109,38 @@ export function filterValidIndexEvents(events: Set): Set { console.debug(`Filtered index events: ${events.size} events remaining.`); return events; } + +/** + * Async version of Array.findIndex() that runs sequentially. + * Returns the index of the first element that satisfies the provided testing function. + * @param array The array to search + * @param predicate The async testing function + * @returns A promise that resolves to the index of the first matching element, or -1 if none found + */ +export async function findIndexAsync( + array: T[], + predicate: (element: T, index: number, array: T[]) => Promise +): Promise { + for (let i = 0; i < array.length; i++) { + if (await predicate(array[i], i, array)) { + return i; + } + } + return -1; +} + +// Extend Array prototype with findIndexAsync +declare global { + interface Array { + findIndexAsync( + predicate: (element: T, index: number, array: T[]) => Promise + ): Promise; + } +} + +Array.prototype.findIndexAsync = function( + this: T[], + predicate: (element: T, index: number, array: T[]) => Promise +): Promise { + return findIndexAsync(this, predicate); +};