Contains utility functions and classes in the style of dart:collection to make working with collections easier

Related tags

Utilities collection
Overview

Contains utility functions and classes in the style of dart:collection to make working with collections easier.

Algorithms

The package contains functions that operate on lists.

It contains ways to shuffle a List, do binary search on a sorted List, and various sorting algorithms.

Equality

The package provides a way to specify the equality of elements and collections.

Collections in Dart have no inherent equality. Two sets are not equal, even if they contain exactly the same objects as elements.

The Equality interface provides a way to define such an equality. In this case, for example, const SetEquality(IdentityEquality()) is an equality that considers two sets equal exactly if they contain identical elements.

Equalities are provided for Iterables, Lists, Sets, and Maps, as well as combinations of these, such as:

const MapEquality(IdentityEquality(), ListEquality());

This equality considers maps equal if they have identical keys, and the corresponding values are lists with equal (operator==) values.

Iterable Zip

Utilities for "zipping" a list of iterables into an iterable of lists.

Priority Queue

An interface and implementation of a priority queue.

Wrappers

The package contains classes that "wrap" a collection.

A wrapper class contains an object of the same type, and it forwards all methods to the wrapped object.

Wrapper classes can be used in various ways, for example to restrict the type of an object to that of a supertype, or to change the behavior of selected functions on an existing object.

Features and bugs

Please file feature requests and bugs at the issue tracker.

Comments
  • Add Iterable.elementAtOrNull extension

    Add Iterable.elementAtOrNull extension

    Add a extension function for List getOrNull(int index) returns a element at the given [index] of this list, if [index] out of bounds, return null

    Example:

    final list = [1,2,3];
    list.getOrNull(1); // 2
    list.getOrNull(10); // null
    
    cla: yes 
    opened by windrunner414 14
  • const UnmodifiableSetView.empty() constructor

    const UnmodifiableSetView.empty() constructor

    It would be really nice to have a const Unmodifiable{List/Map/Set}View.empty() constructor or Empty{List/Map/Set} classes with const constructor because only const values can be used as default arguments for optional parameters! The is a const Iterable.empty() constructor in Dart:core, but the same for List/Map/Set is missing and the List/Map/Set.from{Iterable}(Iterable i) constructors don't help us because they aren't const.

    enhancement 
    opened by simon-void 13
  • An implementation of Map. That allows for multiple inserts of a ke y …

    An implementation of Map. That allows for multiple inserts of a ke y …

    …retaining all inserted values and always returning the last inserted value through standard Map API. Additional method, multiple, allows access to all inserted values for a given key. Will be used in http and http_server packages for non-breaking extension of functionality for form parameters and header parameters that have multiple values for the same key.

    Referenced Issues: https://github.com/dart-lang/http/issues/47 https://github.com/dart-lang/http/issues/24 https://github.com/dart-lang/http_server/issues/35 https://github.com/dart-lang/sdk/issues/28142

    cla: yes 
    opened by rwrozelle 12
  • CombinedMapView does not maintain keys uniqueness

    CombinedMapView does not maintain keys uniqueness

    The following test fails:

    final map = CombinedMapView([{'1': 1, '2': 2, '3': 3}, {'2': 22, '4': 44}]);
    expect(map.length, equals(4));
    expect(map.keys.toList(), equals(['1', '2', '3', '4']));
    

    The first expectation fails because length returns 5. The second, because keys returns ['1', '2', '3', '2', '4'].

    This seems to violate Map's interface, which says:

    There is a finite number of keys in the map, and each key has exactly one value associated with it.
    

    This was a problem for me because I needed something that looks just like a normal Map but based on two other Maps, and which lets a map coming first "override" values on the map coming later in the list of maps. I believe that's the main purpose of combining maps (possibly unmodifiable), but due to this issue, it can't be used like that.

    opened by renatoathaydes 11
  • binarySearch in 'package:collection/algorithms.dart' should return insertion point

    binarySearch in 'package:collection/algorithms.dart' should return insertion point

    Originally opened as dart-lang/sdk#22040

    This issue was originally filed by [email protected]


    What steps will clearly show the issue / need for enhancement?

    1. [binarySearch] returns -1 in case an element is not found
    2. Often in a program one would first try to find an element in a list and if it is not in the next step is to add it. Knowing where it has to be added avoids to sort the list again after the addition.
    3. It is very easy for [binarySearch] to return the insertion point, no additional calculation is needed.

    What is the current output?

    -1 if an element is not found.

    What would you like to see instead?

    -insertion point - 1

    What version of the product are you using? On what operating system?

    collection 1.1.0, Windows 7

    Please provide any additional information below.

    My proposal for the reworked code:

      /// Returns a position of the [key] in [sortedList], if it is there.   ///   /// If the list isn't sorted according to the [compare] function, the result is unpredictable. If   /// [compare] is omitted, it defaults to calling [Comparable.compareTo] on the objects.   ///   /// Returns [-insertion point - 1] if [key] is not in the list. The insertion point is defined as   /// the point at which the key would be inserted into the list: the index of the first element   /// greater than the key, or [list.length] if all elements in the list are less than the specified   /// key. Note that this guarantees that the return value will be >= 0 if and only if the key is   /// found.   int binarySearch(List sortedList, var key, { int compare(var a, var b) }) {     bool useDefault = compare == null;     int min = 0;     int max = sortedList.length;     while (min < max) {       int mid = min + ((max - min) >> 1);       var element = sortedList[mid];       int comp = useDefault ? element.compareTo(key) : compare(element, key);       if (comp == 0) return mid;       if (comp < 0) min = mid + 1; else max = mid;     }     return -min - 1;   }

    The code also contains a slight enhancement which avoids to have the same method programmed twice as is the case in the current implementation. The enhancement is not performance negative but halves the code size!

    enhancement 
    opened by DartBot 11
  • Add extension methods to package:collection.

    Add extension methods to package:collection.

    Add a number of useful extension methods to List and Iterable, and to a few other types.

    A good part of these extensions are backed by the algorithms of algorithms.dart, which is expanded to support them:

    • Added quickSort.
    • Add extra optional Random argument to shuffle.
    • Generalize some of the functions in algorithms.dart to work on specific properties of the objects (binarySearchBy, lowerBoundBy, insertionSortBy, quickSortBy, mergeSortBy).
    cla: yes 
    opened by lrhn 10
  • HeapPriorityQueue doesn't let one iterate in unsorted order

    HeapPriorityQueue doesn't let one iterate in unsorted order

    My code has several huge priority queues using HeapPriorityQueue, where it occasionally needs to consider all the elements in the queue where the order doesn't matter (e.g. to tally up how long it will take to process the queue, or to consider all the items and move a few to another queue if circumstances changes).

    However, HeapPriorityQueue only offers toList() and toSet() for this purpose. However, they spend O(nlogn) to sort the queue (and I need a linear time algorithm) and duplicates the data structure (I just need constant memory). The only way to iterate the queue in linear time in unsorted order is to use removeAll(), however it is destructive.

    The HeapPriorityQueue internally just uses a list to manage the data structure, which is what is returned by removeAll(). It could easily gain a Iterable<E> get unsorted getter or something that returns the backing data structure with the appropriate concurrent modification protections.

    This is probably a breaking change and needs a major version bump in case anyone implemented HeapPriorityQueue.

    I'm currently working around the issue associating each priority queue with a Set in my mod, however it duplicates the amount of memory spent on the queues.

    enhancement 
    opened by sortie 8
  • Strong mode complains about Equality default constructor params.

    Strong mode complains about Equality default constructor params.

    E.g., "const ListEquality()" causes the following warnings:

    [INFO] The object type 'DefaultEquality' cannot be assigned to the field '_elementEquality', which has type 'Equality' [CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH] [INFO] The object type 'DefaultEquality' cannot be assigned to a parameter of type 'Equality' [CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH]

    This is because of the type mismatch in ListEquality's default constructor parameters: final Equality _elementEquality; const ListEquality([Equality elementEquality = const DefaultEquality()]) : _elementEquality = elementEquality;

    and can be fixed by adding the generic type. I'll send a pull request for this and similar classes.

    duplicate 
    opened by har79 8
  • Add an empty unmodifiable map implementation

    Add an empty unmodifiable map implementation

    Adds an EmptyUnmodifiableMap implementation which provides a const constructor.

    The Mixin classes within unmodifiable_wrappers.dart were changed from abstract class to mixin to modernize the code. This allowed the EmptyUnmodifiableMap to have a const constructor without also defining a const constructor in UnmodifiableMapMixin.

    cla: yes 
    opened by donny-dont 7
  • Add an option (possibly the default?) for DeepCollectionEquality to handle self-referential structures

    Add an option (possibly the default?) for DeepCollectionEquality to handle self-referential structures

    <img src="https://avatars.githubusercontent.com/u/188?v=3" align="left" width="96" height="96"hspace="10"> Issue by nex3 Originally opened as dart-lang/sdk#18729


    Sometimes it's useful to be able to compare nested object structures that can contain self-referential loops. Currently DeepCollectionEquality causes a stack overflow when passed such structures, but it would be nice if it could handle them. This could be done either as a configuration option or as the default if the prospect of storing back-references isn't too worrisome.

    Currently the YAML package has its own custom implementation of deep equality, but it would be nice if it could use the standard implementation instead.

    enhancement 
    opened by DartBot 7
  • CombinedMapView.keys fix

    CombinedMapView.keys fix

    Fixes https://github.com/dart-lang/collection/issues/109

    Adds a custom iterable/iterator that can filter out duplicates and use that for the CombineMapView.keys getter.

    Update tests to contain duplicates in maps, and ensure the keys/values from the earlier maps are the ones that are returned.

    Updates the changelog and docs to no longer claim O(maps) for the length getter. This now requires iteration of all items and is O(total map entries).

    Prepare to publish as 1.14.12

    cla: yes 
    opened by jakemac53 6
  • `CanonicalizedMap`: new `copy`, `toMap` and `toMapOfCanonicalKeys` methods

    `CanonicalizedMap`: new `copy`, `toMap` and `toMapOfCanonicalKeys` methods

    • copy: copies a CanonicalizedMap instance without recalculating the canonical values of the keys.
    • toMap: creates a Map<K,V> (with the original key values).
    • toMapOfCanonicalKeys: creates a Map<C,V> (with the canocalized keys).
    opened by gmpassos 0
  • lastOrNull is suboptimal

    lastOrNull is suboptimal

    I believe the current implementation produces two iterators: one for isEmpty and one for last:

      /// The last element, or `null` if the iterable is empty.
      T? get lastOrNull {
        if (isEmpty) return null;
        return last;
      }
    

    Unless I'm missing something here, I think this is suboptimal, especially when using this on a lazy Iterable (for example, giantList.where(someCondition).

    opened by alanrussian 0
  • RFC: Add enumerated extension

    RFC: Add enumerated extension

    I have found this extension to be useful, it allows someone to skip the common for loop pattern for accessing elements. It also supersedes the need for specialized methods like mapIndexed, whereIndexed, (I count 14 in this package). BUT the value seems low because technically we have asMap and these specialized methods already

    Before

    for(var i = 0; i < foo.length; i++){
      print(i);
      print(foo[i]);
    }
    
    foo.forEach((value){
      final index = foo.indexOf(value);
      print(index);
      print(value);
    }
    

    After

    for(final element in foo.enumerated){
      print(element.index);
      print(element.value);
    }
    
    foo.enumerated.forEach((element){
      print(element.index);
      print(element.value);
    }
    

    Related issues

    Lots of JavaScript developers rely on their overloadable map method which allows optionally accessing the index, so tutorials like this are created to shim this missing functionality https://fireship.io/snippets/dart-how-to-get-the-index-on-array-loop-map/

    This is a common question on Stack Overflow

    Screen Shot 2022-12-21 at 8 49 44 AM

    Entire videos on YouTube are dedicated to helping people with this

    https://www.youtube.com/watch?v=HLMzibT2Wms

    There are some related issues here, although admittedly they are closed

    https://github.com/dart-lang/sdk/issues/49589 https://github.com/dart-lang/sdk/issues/33965

    opened by lukepighetti 0
  • Update to 1.17.0

    Update to 1.17.0

    I cant update to version 1.17.0, i got this message

    Because every version of flutter_test from sdk depends on collection 1.16.0 and app depends on collection ^1.17.0, flutter_test from sdk is forbidden. So, because app depends on flutter_test from sdk, version solving failed. pub get failed (1; So, because app depends on flutter_test from sdk, version solving failed.)

    Flutter version : 3.3.8

    opened by ARASHz4 5
  • [proposal] add Json typedef

    [proposal] add Json typedef

    it would be nice if we could stop using Map<String,dynamic> for json and have something like

    typedef Json = Map<String,Object?>;
    

    if find this would

    • reduce bolilerplate
    • be more accurate
    • be more readable
    opened by iapicca 1
  • [suggestion] whereIn, whereNotIn, whereEqual, whereNotEqual

    [suggestion] whereIn, whereNotIn, whereEqual, whereNotEqual

    • whereIn, whereNotIn, eg: currentPictures.whereNot(removedPictures.contain) vs currentPictures.whereNotIn(removedPictures)
    • whereEqual, whereNotEqual eg: currentMedias.whereNot((media) => media == removedMedia) vs currentMedias.whereNotEqual(removedMedia)

    Just a suggestion to improve readability, especially for the first one. Those seems vanilla enough to warrant an addition.

    opened by cedvdb 0
Releases(1.14.10)
  • 1.14.10(Jun 12, 2018)

  • 1.14.9(Mar 20, 2018)

    • Fixed bugs where QueueList, MapKeySet, and MapValueSet did not adhere to the contract laid out by List.cast, Set.cast and Map.cast respectively. The returned instances of these methods now correctly forward to the existing instance instead of always creating a new copy.
    Source code(tar.gz)
    Source code(zip)
  • 1.14.7(Mar 13, 2018)

  • 1.14.0(Mar 26, 2017)

    1.14.0

    • Add CombinedListView, a view of several lists concatenated together.
    • Add CombinedIterableView, a view of several iterables concatenated together.
    • Add CombinedMapView, a view of several maps concatenated together.
    Source code(tar.gz)
    Source code(zip)
Owner
Dart
Dart is an open-source, scalable programming language, with robust libraries and runtimes, for building web, server, and mobile apps.
Dart
Provides simple conversion between Dart classes and Protobuf / Fixnum classes used in gRPC.

grpc_protobuf_convert Provides simple conversion between Dart classes and Protobuf / Fixnum classes used in gRPC. Using the library Add the repo to yo

null 2 Nov 1, 2022
Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Google 905 Jan 2, 2023
This library contains methods that make it easy to consume Mpesa Api.

This library contains methods that make it easy to consume Mpesa Api. It's multi-platform, and supports CLI, server, mobile, desktop, and the browser.

Eddie Genius 3 Dec 15, 2021
An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Leynier Gutiérrez González 7 Aug 24, 2022
Automatically generate usecase classes from your repository class definition in Dart and Flutter

Repo Case Automatically generate usecase classes from your repository class definition in Dart and Flutter. Check out the official guide on repo_case

Sandro Maglione 5 Jul 30, 2022
Dart Code Generator for generating mapper classes

Smartstruct - Dart bean mappings - the easy nullsafe way! Code generator for generating type-safe mappers in dart, inspired by https://mapstruct.org/

Nils 28 Nov 29, 2022
A CLI tool to help generate dart classes from json returned from API

Json 2 Dart Command line utility Important note There is already a package called json2dart so this package will be called json2dartc ! This project w

Adib Mohsin 38 Oct 5, 2022
A simple Flutter / Dart Utility class for converting complex objects to uri and query string

A simple Flutter / Dart Utility class for converting complex or nested objects to uri and query strings you can follow the the article on how this cla

Opata Joshua 5 Sep 7, 2022
Uproot(uprt) is a multi-platform (Windows, MacOs, and Linux) command line utility written in Dart to convert a router's DHCP IP Reservations between routers

UPROOT Uproot(uprt) is a multi-platform (Windows, MacOs, and Linux) command line utility written in Dart to convert a router's DHCP IP Reservations be

GeekVisit 73 Jan 1, 2023
A pure dart package to apply useful rate limiting strategies on regular functions.

Rate limiting is a strategy for limiting an action. It puts a cap on how often someone can repeat an action within a certain timeframe. Using rate_limiter we made it easier than ever to apply these strategies on regular dart functions.

Stream 24 Dec 14, 2022
FaaS (Function as a service) framework for writing portable Dart functions

Functions Framework for Dart This is a community-supported project, meaning there is no official level of support. The code is not covered by any SLA

Google Cloud Platform 485 Dec 26, 2022
A Dart testing utility for asserting that some code emits a compilation error.

A Dart testing utility for asserting that some code emits a compilation error.

Remi Rousselet 32 Dec 11, 2022
A Pure Dart Utility library that checks for an Active Internet connection

This Code comes from https://github.com/komapeb/data_connection_checker * ?? Internet Connection Checker A Pure Dart Utility library that checks for a

Rounak Tadvi 61 Nov 25, 2022
A flutter package with classes to help testing applications using the canvas

Canvas test helpers MockCanvas is a utility class for writing tests for canvas operations. It supports the same API as the regular Canvas class from d

Blue Fire 12 Jan 31, 2022
Rows lint contains a set of lint rules for dart projects used by projects at Rows GmbH

Rows lint contains a set of lint rules for dart projects used by projects at Rows GmbH

rows 6 Apr 12, 2022
Extension functions on ValueListenable that allows you to work with them almost as if it was a synchronous stream.

functional_listener Extension functions on ValueListenable that allows you to work with them almost as if it was a synchronous stream. Each extension

null 54 Oct 9, 2022
A flutter utility to easily create flavors in your flutter application

Flutter Flavorizr A flutter utility to easily create flavors in your flutter application Getting Started Let's start by setting up our environment in

Angelo Cassano 268 Jan 1, 2023
CLI utility to manage MC Server installations

CLI utility to manage MC server installations. Features Install required JDKs Download server files Generate start scripts (with optimized JVM flags)

Michael Rittmeister 14 Nov 18, 2022
Utility to process H264 profile-level-id values

h264_profile_level_id Dart utility to process H264 profile-level-id values based on Google's libwebrtc C++ code. API import 'package:h264_profile_leve

Ibragim Abbasov 2 Apr 22, 2022