How to combine all strings in a nested-list?

dart, fold, list

Solution

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));

Problem

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?

Original source