@@ -13,13 +13,16 @@ const {
13
13
PromiseReject,
14
14
ReflectGet,
15
15
Symbol,
16
+ SymbolAsyncIterator,
17
+ SymbolIterator,
16
18
Uint8Array,
17
19
} = primordials ;
18
20
19
21
const {
20
22
codes : {
21
23
ERR_INVALID_ARG_VALUE ,
22
24
ERR_OPERATION_FAILED ,
25
+ ERR_INVALID_STATE ,
23
26
} ,
24
27
} = require ( 'internal/errors' ) ;
25
28
@@ -217,6 +220,54 @@ function lazyTransfer() {
217
220
return transfer ;
218
221
}
219
222
223
+ function createAsyncFromSyncIterator ( syncIteratorRecord ) {
224
+ const syncIterable = {
225
+ [ SymbolIterator ] : ( ) => syncIteratorRecord . iterator ,
226
+ } ;
227
+
228
+ const asyncIterator = ( async function * ( ) {
229
+ return yield * syncIterable ;
230
+ } ( ) ) ;
231
+
232
+ const nextMethod = asyncIterator . next ;
233
+ return { iterator : asyncIterator , nextMethod, done : false } ;
234
+ }
235
+
236
+ function getIterator ( obj , kind = 'sync' , method ) {
237
+ if ( method === undefined ) {
238
+ if ( kind === 'async' ) {
239
+ method = obj [ SymbolAsyncIterator ] ;
240
+ if ( method === undefined ) {
241
+ const syncMethod = obj [ SymbolIterator ] ;
242
+ const syncIteratorRecord = getIterator ( obj , 'sync' , syncMethod ) ;
243
+ return createAsyncFromSyncIterator ( syncIteratorRecord ) ;
244
+ }
245
+ } else {
246
+ method = obj [ SymbolIterator ] ;
247
+ }
248
+ }
249
+
250
+ const iterator = FunctionPrototypeCall ( method , obj ) ;
251
+ if ( typeof iterator !== 'object' || iterator === null ) {
252
+ throw new ERR_INVALID_STATE . TypeError ( 'The iterator method must return an object' ) ;
253
+ }
254
+ const nextMethod = iterator . next ;
255
+ return { iterator, nextMethod, done : false } ;
256
+ }
257
+
258
+ function iteratorNext ( iteratorRecord , value ) {
259
+ let result ;
260
+ if ( value === undefined ) {
261
+ result = FunctionPrototypeCall ( iteratorRecord . nextMethod , iteratorRecord . iterator ) ;
262
+ } else {
263
+ result = FunctionPrototypeCall ( iteratorRecord . nextMethod , iteratorRecord . iterator , [ value ] ) ;
264
+ }
265
+ if ( typeof result !== 'object' || result === null ) {
266
+ throw new ERR_INVALID_STATE . TypeError ( 'The iterator.next() method must return an object' ) ;
267
+ }
268
+ return result ;
269
+ }
270
+
220
271
module . exports = {
221
272
ArrayBufferViewGetBuffer,
222
273
ArrayBufferViewGetByteLength,
@@ -243,6 +294,8 @@ module.exports = {
243
294
nonOpPull,
244
295
nonOpStart,
245
296
nonOpWrite,
297
+ getIterator,
298
+ iteratorNext,
246
299
kType,
247
300
kState,
248
301
} ;
0 commit comments