Skip to content

Commit

Permalink
Implemented iterable/flattenDeep.
Browse files Browse the repository at this point in the history
Fixes #8.
  • Loading branch information
ivoreis authored and jussi-kalliokoski committed Jul 2, 2015
1 parent 4af4beb commit b9660dd
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/iterable/flattenDeep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"use strict";

/**
* Yields the elements in the iterable at the given depth.
* Flattening with depth of 1 is the same as doing a plain `flatten()`.
*
* @this {Iterable}
* @param depth The depth that the generator will flatten to.
* @example Basic Usage
*
* ```javascript
* [[[1],[2]]]::flattenDeep(2) // yields [1,2]
* ```
*/

export function * flattenDeep <T> (
depth : number,
) : Iterable {
if ( depth < 0 ) {
yield this;
return;
}

for ( const item of this ) {
yield * item::flattenDeep(depth - 1);
}
};
34 changes: 34 additions & 0 deletions test/spec/iterable/flattenDeepSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use strict";

import { flattenDeep } from "../../../src/iterable/flattenDeep";

describe("flattenDeep()", function () {

it("should throw when trying to flatten a non iterable item", function () {
void function () {
[...[1,2,3]::flattenDeep(1)]
}.should.throw();
})

it("should flatten a simple nested array", function () {
[...[[1],[2]]::flattenDeep(1)].should.deep.equal([1,2]);
});

it("should flattenDeep to 1 level deep", function () {
[...[[[[1]],[2,[3]]]]::flattenDeep(1)].should.deep.equal([[[1]],[2,[3]]]);
});

it("should flattenDeep to 2 levels deep", function () {
[...[[[[1]],[2,[3]]]]::flattenDeep(2)].should.deep.equal([[1],2,[3]]);
});

it("should flattenDeep to 3 levels deep", function () {
[...[[[[1]],[[2],[3]]]]::flattenDeep(3)].should.deep.equal([1,2,3]);
});

it("should flattenDeep set with nested array", function () {
const set = new Set(["a", [1,2,3]]);
[...[set]::flattenDeep(2)].should.deep.equal(["a",1,2,3]);
});

});

0 comments on commit b9660dd

Please sign in to comment.