Is there a way to do a lazy concat of two sequences in Immutable.js? Specifically, I have this algorithm that flattens a tree into a breadth-first sequence:
var Immutable = require('immutable');
var tree = {
value: 'foo',
children: [
{
value: 'bar',
children: [
{ value: 'barOne'},
{ value: 'barTwo'}
]
},
{
value: 'baz',
children: [
{ value: 'baz1'},
{ value: 'baz2'},
{ value: 'baz3'}
]
}
]
};
var flattenTree = function(seq) {
if(!seq.isEmpty()) {
var nextTier = seq.flatMap(function(node){
return node.children;
});
return seq.concat(flattenTree(nextTier));
} else {
return Immutable.Seq();
}
};
var startSeq = Immutable.Seq([tree]);
var seq = flattenTree(startSeq);
var values = seq.map(function(node){ return node.value; });
console.log(values.first());
Unfortunately, the whole tree is evaluated when this is run. I wish I could do
return seq.concat(function(){ return flattenTree(nextTier); });
and have it perform a lazy concat, but it's not supported. Ruby's excellent Hamster gem supports this. What are my alternatives if I want to use Immutable.js? Do any other JS libraries support it? Is there another algorithm that achieves the same thing?
A lazy breadth-first traversal can be achieved with the Iterable API for Immutable.js: