Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9a23d43
commit 6568e83
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} | ||
}; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); | ||
}); |