Created
February 24, 2017 21:29
-
-
Save mattpodwysocki/5ff58711fb0bd883922a1bea3639cfc2 to your computer and use it in GitHub Desktop.
Better zip construction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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