Home > Blockchain >  How to use for of loop with two iterators
How to use for of loop with two iterators

Time:10-10

I'm looking for a way to do something similar to Python :

for a,b in zip(c,d) :

I'm trying to do it with the for... of loop in javascript but I just can't find how... something like :

const b = [2,3,5]
const d = [['e1' , 'e2' , 'e3'], ['i1', 'i2'], 
['o1', 'o2', 'o3', 'o4']] 

for (const a of b, const c of d) {
    instruction(a,c)
}

Thanks

CodePudding user response:

If I look up the zip function, it just combines each entry by index, you should be able to simulate that easily enough with a normal function, but to keep the iterator aspect of it, you can use a generator function

const b = [2,3,5];
const d = [['e1' , 'e2' , 'e3'], ['i1', 'i2'], 
['o1', 'o2', 'o3', 'o4']];

function *zip( ...iterables ) {
  const inputs = iterables.map( iterator => Array.isArray( iterator ) ? iterator : Array.from( iterator ) );
  const size = Math.min( ...inputs.map( i => i.length ) );
  for (let i = 0; i < size; i  ) {
    yield inputs.map( input => input[i] );
  }
}

console.log( 'iterating with arrays' );
for (const entry of zip(b, d)) {
  console.log( entry );
}

console.log( 'iterating with other iterators' );
for (const entry of zip(b, zip(b, d))) {
  console.log( entry );
}

  • Related