Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine all strings in a nested-list?

Tags:

list

dart

fold

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?

like image 738
Freewind Avatar asked Dec 26 '22 13:12

Freewind


1 Answers

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));
like image 97
Greg Lowe Avatar answered Jan 31 '23 06:01

Greg Lowe