Skip to content

Commit

Permalink
Implemented iterable/zip.
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhedonia authored and jussi-kalliokoski committed Jul 20, 2015
1 parent 9a23d43 commit 6568e83
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/iterable/zip.js
@@ -0,0 +1,36 @@
/**
* Yields groups of elements where the first group contains the first elements
* of all the iterators, second contains the second items and etc. until one
* of the iterators has been exhausted.
*
* @this {Iterable<Iterable<T>>}
* @ntime O(nm)
* @dspace O(m)
* @example Basic Usage
*
* ```javascript
* [ [1,2], [4,5], [6,7] ]::zip() // yields [1,4,6], [2,5,7]
* ```
*/

export function * zip () : Iterable<Iterable<T>> {
const iterators = [...this].map(
(iterable) => iterable[Symbol.iterator]()
);

if ( iterators.length === 0 ) { return; }

while ( true ) {
const zipped = [];

for ( const iterator of iterators ) {
const { value, done } = iterator.next();

if ( done ) { return; }

zipped.push(value);
}

yield zipped;
}
};
38 changes: 38 additions & 0 deletions test/spec/iterable/zipSpec.js
@@ -0,0 +1,38 @@
import { zip } from "../../../src/iterable/zip";

function * iter () {
let i = 0;

while ( true ) {
yield ++i;
}
}

function * iterIter () {
yield iter();
yield [4, 5];
yield [6, 7];
}

describe("zip()", function () {
const zipped = [
[1, 4, 6],
[2, 5, 7],
];

it("should zip empty arrays", function () {
const toZip = [[1, 2, 3],[]];
[...toZip::zip()].should.deep.equal([]);
[...[]::zip()].should.deep.equal([]);
});

it("should zip arrays correctly", function () {
const toZip = [ [1, 2, 3], [4, 5], [6, 7] ];
[...toZip::zip()].should.deep.equal(zipped);
});

it("should zip iterators correctly", function () {
const toZip = iterIter();
[...toZip::zip()].should.deep.equal(zipped);
});
});

0 comments on commit 6568e83

Please sign in to comment.