Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created February 24, 2017 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/5ff58711fb0bd883922a1bea3639cfc2 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/5ff58711fb0bd883922a1bea3639cfc2 to your computer and use it in GitHub Desktop.
Better zip construction
'use strict';
import { IIterable, IIterator } from '../iterable.interfaces';
import { Iterable } from '../iterable';
import { Iterator } from '../iterator';
import { MapIterable } from './map';
export class ZipIterator<T> extends Iterator<T> {
private _it: IIterator<T>[];
constructor(...it: IIterator<T>[]) {
super();
this._it = it;
}
next() {
let len = this._it.length, results = [], next;
for (var i = 0; i < len; i++) {
next = this._it[i].next();
if (next.done) { return next; }
results.push(next.value);
}
return { done: false, value: results };
}
}
export class ZipIterable<T> extends Iterable<T> {
private _source: IIterable<T>[];
constructor(...source: IIterable<T>[]) {
super();
this._source = source;
}
[Symbol.iterator]() {
let results = [], len = this._source.length, i = 0;
for(; i < len; i++) {
results.push(this._source[i][Symbol.iterator]());
}
return new ZipIterator<T>(...results);
}
}
export function zip<T>(...args: IIterable<T>[]): Iterable<T> {
return new ZipIterable<T>(...args);
}
export function zipWith<T, TResult>(
fn: (...args: T[]) => TResult,
...args: IIterable<T>[]): Iterable<TResult> {
const zipped = new ZipIterable<T>(...args);
return new MapIterable<T[], TResult>(zipped, zipArgs => fn(...zipArgs));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment