From 2b82d72d84de008e0fc10a80dc9948cddb6abf39 Mon Sep 17 00:00:00 2001 From: Aditi Khare Date: Wed, 31 Jul 2024 14:59:06 -0400 Subject: [PATCH] requested changes --- src/cursor/abstract_cursor.ts | 36 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/cursor/abstract_cursor.ts b/src/cursor/abstract_cursor.ts index 8d069787cb..a9246398cd 100644 --- a/src/cursor/abstract_cursor.ts +++ b/src/cursor/abstract_cursor.ts @@ -281,8 +281,8 @@ export abstract class AbstractCursor< } /** Returns current buffered documents */ - readBufferedDocuments(number?: number): TSchema[] { - const bufferedDocs: TSchema[] = []; + readBufferedDocuments(number?: number): NonNullable[] { + const bufferedDocs: NonNullable[] = []; const documentsToRead = Math.min( number ?? this.documents?.length ?? 0, this.documents?.length ?? 0 @@ -457,29 +457,33 @@ export abstract class AbstractCursor< * results when this cursor had been previously accessed. In that case, * cursor.rewind() can be used to reset the cursor. */ - async toArray(): Promise { + async toArray(transform_temp?: (doc: TSchema) => any): Promise { const array: TSchema[] = []; - // when each loop iteration ends,documents will be empty and a 'await (const document of this)' will run a getMore operation + this.transform = transform_temp; + // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty + // then, the 'await of' syntax will run a getMore call for await (const document of this) { array.push(document); - let docs = this.readBufferedDocuments(); + const docs = this.readBufferedDocuments(); if (this.transform != null) { - docs = await Promise.all( - docs.map(async doc => { - if (doc != null) { - return await this.transformDocument(doc); - } else { - throw Error; - } - }) - ); + for (const doc of docs) { + array.push(await this.transformDocument(doc)); + } + } else { + array.push(...docs); } - array.push(...docs); } return array; } + async toArrayOld(): Promise { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } /** * Add a cursor flag to the cursor * @@ -820,7 +824,7 @@ export abstract class AbstractCursor< } /** @internal */ - private async transformDocument(document: NonNullable): Promise { + private async transformDocument(document: NonNullable): Promise> { if (this.transform == null) return document; try {