Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cleanly map / sort / fold / sort / expand using only cascades or chained calls, in Dart?

Tags:

dart

I would like to perform the following operations on a source list:

  • map
  • toList
  • sort
  • fold
  • sort
  • expand
  • toList

Some of these methods, like map and toList are chainable, because they return a non-null object. However, the sort method returns void as it operates on a List and does not return a list.

Dart has a method cascade operator, which works great for method calls that do not return this or another object.

I'm having a hard time writing the above sequence of calls without resorting to assigning a variable after the sort and then starting the chain of calls again.

I'd like to write the equivalent of:

return thing
         .map(...)
         .toList()
         .sort(...)
         .fold(...)
         .sort(...)
         .expand(...)
         .toList();

The closest I can get is:

var thing
      .map(...)
      .toList()
        ..sort(...);

var otherThing = thing
                   .fold(...)
                     ..sort(...);

var finalThing = otherThing.expand(...).toList();

Is there a better way? How do I "break out" of the cascade and continue on a chain?

like image 458
Seth Ladd Avatar asked Dec 08 '13 07:12

Seth Ladd


1 Answers

Can you add some parens? I guess something like this...

return ((thing
         .map(...)
         .toList()..sort(...))
           .fold(...)..sort(...))
             .expand(...)
             .toList();
like image 178
Greg Lowe Avatar answered Nov 15 '22 10:11

Greg Lowe