jussi-kalliokoski / trine

A utility library for modern JavaScript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

implement `iterator/flatten`

jussi-kalliokoski opened this issue · comments

@ivoreis I'd rather not make flatten deep by default, and even with a flattenDeep implementation I'd keep it so that the user specifies the level of recursion - keeps things less magical and more performant, and also discourages weird data structures (your implementation would flatten [[[[1]], [2, [3]]] to [1, 2, 3]). Avoids nasty surprises as well, e.g. [[new Map([[1,"a"], [2, "b"]]), new Map([[3, "c"]])], [new Map([[4, "d"]])] would be flattened to [1, "a", 2, "b", 3, "c", 4, "d"].

@jussi-kalliokoski I also prefer simplicity and I think splitting flatten and flattenDeep should be a good idea. In the case of a nested array with a map what do you think should be the expected outcome if we tried to flatten it?

@ivoreis : I think

[...[new Map([[1, 2]]), new Map([[3, 4]])]::flatten()].should.deep.equal([[1, 2], [3, 4]]);
[...[new Map([[1, 2]]), new Map([[3, 4]])]::flattenDeep(2)].should.deep.equal([1, 2, 3, 4]);

This seems like expectable behavior to me and allows for example the following:

function combineObjectsIntoAMap () {
  return this
    ::map(entries)
    ::flatten()
    ::to(Map);
}

[{ a: 1 }, { b: 2 }]::combineObjectsIntoAMap(); // returns Map { a: 1, b: 2 }