Logo

Programming-Idioms

  • JS
  • Go

Idiom #143 Iterate alternatively over two lists

Iterate alternatively over the elements of the lists items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.

for i := 0; i < len(items1) || i < len(items2); i++ {
	if i < len(items1) {
		fmt.Println(items1[i])
	}
	if i < len(items2) {
		fmt.Println(items2[i])
	}
}
import "fmt"
for i := range min(len(items1), len(items2)) {
	fmt.Println(items1[i])
	fmt.Println(items2[i])

}
const iterator1 = items1[Symbol.iterator]()
const iterator2 = items2[Symbol.iterator]()

let result1 = iterator1.next()
let result2 = iterator2.next()

while(!(result1.done && result2.done)) {
  if (!result1.done) {
    console.log(result1.value)
    result1 = iterator1.next()
  }
  if (!result2.done) {
    console.log(result2.value)
    result2 = iterator2.next()
  }
}

Approach that purely uses Iterators, similar to the Java Iterator example
const shorter = _items1.length > _items2.length ? _items2 : _items1;
const longer = _items1.length <= _items2.length ? _items2 : _items1;
shorter.map((m, i) => {
  console.log(m);
  console.log(longer[i]);
});

will limit each array to the length of the shortest array
(doseq [i (interleave items1 items2)]
  (println i))

interleave can receive any number of items, but truncates when any of them is exhausted

New implementation...