I have a list, which contains multi-level nested lists. Each list can have strings and other type instances.
E.g.
var list = [ 'a', 'w', ['e', ['f', new Object(), 'f'], 'g'], 't', 'e'];
I want to write a function (say compress
) to combine strings with their siblings, and leave other type instances untouched, and finally, get a list which doesn't have nested list.
compress(list) { // how to ? }
And the result of compress(list)
will be:
['awef', new Object(), 'fgte']
Is it quick and clear solution for it?
Terse and functional FTW
List compress(Iterable iterable) => concat(flatten(iterable));
Iterable flatten(Iterable iterable) =>
iterable.expand((e) => e is Iterable ? flatten(e) : [e]);
List concat(Iterable iterable) => iterable.fold([], (list, e) =>
list..add((e is String && list.isNotEmpty && list.last is String)
? list.removeLast() + e : e));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With