JSFiddle - React, Tailwind, and code Playground

by brigand

HTML

<pre id="out"></pre>

JavaScript

function* peek(iterable) {
	let previous = null;
	for (const item of iterable) {
		if (previous) {
			yield [previous, item]
		}
		previous = item;
	}
}

class Peek {
	constructor(iterable) {
	  this.iter = iterable[Symbol.iterator]();
    this.previous = null;
  }
  
  next() {
	  let next = this.iter.next();
    if (next.done) {
	    return next;
    }
    
		let result = null;
    
  	if (this.previous) {
    	result = { done: false, value: [this.previous, next.value] };
    }
    
    this.previous = next.value;
    
    if (!result) {
	    return this.next();
    }
    
    return result;
  }
  
  [Symbol.iterator]() {
	  return this;
  }
}

function peek2(iterable) {
	return new Peek(iterable);
}


for (const [a, b] of peek2(['W', 'X', 'Y', 'Z'])) {
	out.textContent += `a: ${a}, b: ${b}\n`;
}