Browse Source

Support async find for lazy publication tree nodes

master
buttercat1791 12 months ago
parent
commit
1272d312d9
  1. 14
      src/lib/data_structures/publication_tree.ts
  2. 35
      src/lib/utils.ts

14
src/lib/data_structures/publication_tree.ts

@ -205,11 +205,19 @@ export class PublicationTree implements AsyncIterable<NDKEvent> { @@ -205,11 +205,19 @@ export class PublicationTree implements AsyncIterable<NDKEvent> {
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<PublicationTreeNode>) => (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;
}

35
src/lib/utils.ts

@ -109,3 +109,38 @@ export function filterValidIndexEvents(events: Set<NDKEvent>): Set<NDKEvent> { @@ -109,3 +109,38 @@ export function filterValidIndexEvents(events: Set<NDKEvent>): Set<NDKEvent> {
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<T>(
array: T[],
predicate: (element: T, index: number, array: T[]) => Promise<boolean>
): Promise<number> {
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<T> {
findIndexAsync(
predicate: (element: T, index: number, array: T[]) => Promise<boolean>
): Promise<number>;
}
}
Array.prototype.findIndexAsync = function<T>(
this: T[],
predicate: (element: T, index: number, array: T[]) => Promise<boolean>
): Promise<number> {
return findIndexAsync(this, predicate);
};

Loading…
Cancel
Save