File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -387,6 +387,11 @@ This is a major release and breaks backwards compatibility.
387387
388388#### Cursor API
389389
390+ - Added ` cursor.flatMap ` method
391+
392+ This method behaves similarly to the ` Array ` method ` flatMap ` but operates
393+ on the cursor directly like ` cursor.map ` does.
394+
390395- Added support for ` for await ` in ` ArrayCursor ` ([ #616 ] ( https://github.com/arangodb/arangojs/pull/616 ) )
391396
392397 It is now possible to use ` for await ` to iterate over each item in a cursor
Original file line number Diff line number Diff line change @@ -250,6 +250,29 @@ export class ArrayCursor<T = any> {
250250 return result ;
251251 }
252252
253+ /**
254+ * TODO
255+ */
256+ async flatMap < U = any > (
257+ fn : ( value : T , index : number , self : ArrayCursor < T > ) => U
258+ ) : Promise < U [ ] > {
259+ let index = 0 ;
260+ let result : any [ ] = [ ] ;
261+ while ( this . _result . length || this . hasMore ) {
262+ while ( this . _result . length ) {
263+ const value = fn ( this . _result . shift ( ) ! , index , this ) ;
264+ if ( Array . isArray ( value ) ) {
265+ result . push ( ...value ) ;
266+ } else {
267+ result . push ( value ) ;
268+ }
269+ index ++ ;
270+ }
271+ if ( this . hasMore ) await this . _more ( ) ;
272+ }
273+ return result ;
274+ }
275+
253276 /**
254277 * TODO
255278 */
Original file line number Diff line number Diff line change @@ -158,6 +158,23 @@ describe("Cursor API", () => {
158158 expect ( results ) . to . eql ( aqlResult . map ( ( value ) => value * 2 ) ) ;
159159 } ) ;
160160 } ) ;
161+ describe ( "cursor.flatMap" , ( ) => {
162+ it ( "flat-maps all result values over the callback" , async ( ) => {
163+ const results = await cursor . flatMap ( ( value ) => [ value , value * 2 ] ) ;
164+ expect ( results ) . to . eql (
165+ aqlResult
166+ . map ( ( value ) => [ value , value * 2 ] )
167+ . reduce ( ( acc , next ) => {
168+ acc . push ( ...next ) ;
169+ return acc ;
170+ } , [ ] as number [ ] )
171+ ) ;
172+ } ) ;
173+ it ( "doesn't choke on non-arrays" , async ( ) => {
174+ const results = await cursor . flatMap ( ( value ) => value * 2 ) ;
175+ expect ( results ) . to . eql ( aqlResult . map ( ( value ) => value * 2 ) ) ;
176+ } ) ;
177+ } ) ;
161178 describe ( "cursor.reduce" , ( ) => {
162179 it ( "reduces the result values with the callback" , async ( ) => {
163180 const result = await cursor . reduce ( ( a , b ) => a + b ) ;
You can’t perform that action at this time.
0 commit comments