@@ -13,13 +13,16 @@ const {
1313 PromiseReject,
1414 ReflectGet,
1515 Symbol,
16+ SymbolAsyncIterator,
17+ SymbolIterator,
1618 Uint8Array,
1719} = primordials ;
1820
1921const {
2022 codes : {
2123 ERR_INVALID_ARG_VALUE ,
2224 ERR_OPERATION_FAILED ,
25+ ERR_INVALID_STATE ,
2326 } ,
2427} = require ( 'internal/errors' ) ;
2528
@@ -217,6 +220,54 @@ function lazyTransfer() {
217220 return transfer ;
218221}
219222
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+
220271module . exports = {
221272 ArrayBufferViewGetBuffer,
222273 ArrayBufferViewGetByteLength,
@@ -243,6 +294,8 @@ module.exports = {
243294 nonOpPull,
244295 nonOpStart,
245296 nonOpWrite,
297+ getIterator,
298+ iteratorNext,
246299 kType,
247300 kState,
248301} ;
0 commit comments