Skip to content
Subhajit Sahu edited this page Dec 5, 2022 · 17 revisions

Flatten nested map to given depth.

Alternatives: flat, flatMap.


function flat(x, n, fm, ft)
// x:  a nested map
// n:  maximum depth [-1 ⇒ all]
// fm: map function (v, k, x)
// ft: test function for flatten (v, k, x) [is]
const map = require('extra-map');

var x = new Map([
  ['ab', new Map([
    ['a', 1],
    ['b', 2]
  ])],
  ['cde', new Map([
    ['c', 3],
    ['de', new Map([
      ['d', 4],
      ['e', new Map([
        ['e', 5]
      ])]
    ])]
  ])]
]);
map.flat(x);
// → Map(5) { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 }

map.flat(x, 1);
// → Map(4) {
// →   'a' => 1,
// →   'b' => 2,
// →   'c' => 3,
// →   'de' => Map(2) { 'd' => 4, 'e' => Map(1) { 'e' => 5 } }
// → }

map.flat(x, 2);
// → Map(5) {
// →   'a' => 1,
// →   'b' => 2,
// →   'c' => 3,
// →   'd' => 4,
// →   'e' => Map(1) { 'e' => 5 }
// → }


References

Clone this wiki locally