superpower 0.3.1

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new79

Logo

Travis (.com) branch Coveralls github Version Runtime GitHub license

Easy to use wrappers for Lists, Maps and Iterables with many handy functions.

Inspired by Kotlin.

Resources:

Get started 🎉

Just wrap your existing List with $(myList) or create a new empty list with $() and you are good to go.

var superList = $([1, 10, 2, 9, null, 3, 8, 4, 7, 5, 6]);
superList
    .slice(2, -2) // [2, 9, null, 3, 8, 4, 7]
    .whereNotNull() // [2, 9, 3, 8, 4, 7]
    .whereIndexed((_, index) => index % 2 == 1) // [9, 8, 7]
    .sum(); // 24

Iterables can be wrapped with $it(myIterable) and Maps with $map(myMap).

Introduction to superpowers ❤️

Negative indices

This is one of the coolest features: You can use negative indices which start at the last element of the list: list[-1] is the same as list[list.length - 1].

Here is a sample with negative indices:

// Negative indices: -4   -3   -2   -1
var superlist =  $([ '0', '1', '2', '3']);
//             Access this ^ item:
var positiveItem = positiveIndices[1]; // 1
var negativeItem = negativeIndices[-3]; // 1

You can use negative indices on all new and existing methods of $List and $Iterable.

firstOrNull & firstOrNullWhere

Find the first element of the collection matching a predicate:

var list = $(['This', 'is', 'a', 'Test']);
var first = list.firstOrNull; // 'This'
var firstWhere = list.firstOrNullWhere((s) => s.length <= 2); // 'is'
var firtNull = list.firstOrNullWhere((s) => s.length > 4); // null

elementAtOrNull & elementAtOrElse

Get the element at an index or null if the index does not exist:

var list = $([0, 1, 2, 3, 4, 5, 6]);
var second = list.elementAtOrNull(1); // 1
var highIndexNull = list.elementAtOrNull(10); // null
var highIndexDefault = list.elementAtOrDefault(10, -1); // -1

slice

Get a sublist of the collection:

var list = $([0, 1, 2, 3, 4, 5]);
var last = list.slice(-1); // [5]
var lastHalf = list.slice(3); // [3, 4, 5]
var allButFirstAndLast = list.slice(1,-2); // [1, 2, 3, 4]

drop & dropLast

Get a list containing all elements except first n elements:

var list = $([0, 1, 2, 3, 4, 5]);
var lastElements = list.drop(3); // [3, 4, 5]
var firstElements = list.dropLast(3); // [0, 1, 2]
var middleElements = list.drop(2).dropLast(2); // [2, 3]

contentEquals

Compare two lists:

var list = $(['some', 'items']);
var equals1 = list.contentEquals(['some', 'items']); // true
var equals2 = list.contentEquals(['SOME', 'items']); // false

sortedBy & thenBy

Sort lists by multiple properties

class Dog {
    String name;
    String age;

    Dog(this.name, this.age);
}

var dogs = $();
dogs.add(Dog("Tom", 3));
dogs.add(Dog("Charlie", 7));
dogs.add(Dog("Charlie", 2));
dogs.add(Dog("Cookie", 4));
dogs.add(Dog("Bark", 1));

var sorted = dogs
    .sortedBy((dog) => dog.name)
    .thenByDescending((dog) => dog.age);
// Bark, Cookie, Charlie (7), Charlie (2), Tom

minBy & maxBy

Get the smallest or largest element from a list:

//Take dogs list from example above
var firstDogByName = dogs.minBy((dog) => dog.name); // Bark
var oldestDog = dogs.maxBy((dog) => dog.age); // Charlie

distinctBy

Get distinct elements from a list:

//Take dogs list from example above
var dogNames = dogs
    .distinctBy((dog) => dog.name)
    .map((dog) => dog.name);
// ['Tom', 'Charlie', 'Cookie', 'Bark']

flatten

Flatten a list of iterables:

var nestedList = $List([[1, 2, 3], [4, 5, 6]]);
var flattened = nestedList.flatten(); // [1, 2, 3, 4, 5, 6]

many more superpowers

There are many more handy superpowers (like intersect(), groupBy() and associateWith()) available. Take a look at the Documentation.

$List, $Iterable and $Map 🦄

The wrappers for Lists, Iterables and Maps are $List, $Iterable and $Map they behave as you would expect them to. ($Iterable is lazy loading while $List is not).

There is no need to work with the unwrapped classes. The wrapper classes have the exact same performance as their native counterparts.

Important: Always remember that $List, $Iterable and $Map are wrappers. This means if you remove an item from a $List, it will also be removed from the source list.

var source = [0, 1, 2, 3];

var superList = $(source);
superList.add(4);
//source: [0, 1, 2, 3, 4]

var independantList = $(source).toList();
independantList.add(5);
//source: [0, 1, 2, 3, 4]

Features and bugs

Please file feature requests and bugs at the issue tracker.

Todo ✏️

  • ✔️ most important features for collections
  • ✔️ superpowers for Map
  • even more tests
  • superpowers for other classes?
  • more features for collections
  • more samples in the docs

MIT License

Copyright (c) 2018 Simon Leier

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0.3.0

  • Breaking: $Iterable.whereNotNull -> $Iterable.whereNotNull()
  • Added $Map and $map()
  • Added $Iterable.all(), $Iterable.toMap(), $Iterable.windowed()
  • Added parameter n to $Iterable.cycle()
  • Added more tests
  • Fix wrong naming in docs: sortBy is really called sortedBy (thanks @bltavares)
  • Improved docs and added examples to many functions

0.2.0

  • Remove drop() and dropWhile() from $List and $Iterable (use skip() and skipWhile() instead)
  • Add $it() as short form of $Iterable()
  • Add test cases

0.1.3

  • Add $Iterable.joinToString(), $Iterable.onEach() and $Iterable.shuffled

0.1.2

  • Add $Iterable.mapNotNull()

0.1.1

  • Documentation fixes

0.1.0

  • First release

example/main.dart

import 'package:superpower/superpower.dart';

class Person {
  String name;
  int age;
  $List<String> hobbies;

  Person(this.name, this.age, this.hobbies);
}

var david = Person("David", 24, $(["biking", "swimming"]));
var linda = Person("Linda", 12, $(["cooking", "friends"]));
var amanda = Person("Amanda", 24, $(["friends", "swimming"]));
var paolo = Person("Paolo", 18, $(["swimming", "cooking"]));

void main() {
  var persons = $([david, linda, amanda, paolo]);

  var averageAge = persons.averageBy((p) => p.age);
  print(averageAge);
  // 19.5

  var hobbies = persons.flatMap((p) => p.hobbies).distinct();
  print(hobbies);
  // ["biking", "swimming", "music", "cooking", "friends"]

  var namesByHobbies = hobbies.associateWith((hobby) {
    return persons.mapNotNull((person) {
      if (person.hobbies.contains(hobby))
        return person.name;
      else
        return null;
    });
  });
  print(namesByHobbies);
  // {
  //   "biking": ["David"],
  //   "swimming": ["David", "Amanda", "Paolo"],
  //   "cooking": ["Linda" "Paolo"],
  //   "friends": ["Linda" "Amanda"]
  // }

  var sorted = persons.sortedBy((p) => p.age).thenByDescending((p) => p.name);
  print(sorted);
  // [Linda, Paolo, David, Amanda]

  var groupedByAge = persons.groupBy((p) => p.age);
  print(groupedByAge);
  // {
  //   12: [Linda],
  //   18: [Paolo],
  //   24: [David, Amanda]
  // }

  var legalAge = persons.partition((p) => p.age >= 21);
  print(legalAge);
  // [
  //  [Linda, Paolo],
  //  [David, Amanda]
  // ]

  var sameHobbies = david.hobbies.intersect(amanda.hobbies);
  print(sameHobbies);
  // ["swimming"]
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  superpower: ^0.3.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:superpower/superpower.dart';
  
Version Uploaded Documentation Archive
0.3.1 Sep 19, 2018 Go to the documentation of superpower 0.3.1 Download superpower 0.3.1 archive
0.3.0 Sep 14, 2018 Go to the documentation of superpower 0.3.0 Download superpower 0.3.0 archive
0.2.0 Aug 29, 2018 Go to the documentation of superpower 0.2.0 Download superpower 0.2.0 archive
0.1.3 Aug 29, 2018 Go to the documentation of superpower 0.1.3 Download superpower 0.1.3 archive
0.1.2 Aug 28, 2018 Go to the documentation of superpower 0.1.2 Download superpower 0.1.2 archive
0.1.1 Aug 28, 2018 Go to the documentation of superpower 0.1.1 Download superpower 0.1.1 archive
0.1.0 Aug 28, 2018 Go to the documentation of superpower 0.1.0 Download superpower 0.1.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
59
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
79
Learn more about scoring.

We analyzed this package on Sep 19, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.3

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:superpower/superpower.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
collection >=1.14.11 <1.15.0 1.14.11
Dev dependencies
grinder ^0.8.3
test any