dart-lang / core

This repository is home to core Dart packages.
https://pub.dev/publishers/dart.dev
BSD 3-Clause "New" or "Revised" License
18 stars 7 forks source link

Feature Request: Add `countFrequency` method to `Iterable` in the collection package #679

Open pvlKryu opened 4 months ago

pvlKryu commented 4 months ago

Feature Request: Add countFrequency method to Iterable in the collection package

Description

I would like to propose adding a new method countFrequency to the Iterable class in the collection package. This method would return a Map where the keys are the unique elements from the iterable, and the values are the counts of those elements.

Motivation

A built-in method to count the frequency of elements in an iterable simplifies common tasks that developers often need to implement manually. This addition will enhance the collection package's usability and convenience, providing a standard way to perform this operation.

Proposed Implementation

Add the following extension to lib/src/iterable_extensions.dart:

extension FrequencyCounter<T> on Iterable<T> {
  /// Returns a map where the keys are the unique elements of the iterable
  /// and the values are the counts of those elements.
  Map<T, int> countFrequency() {
    Map<T, int> frequencyMap = {};
    for (var item in this) {
      frequencyMap[item] = (frequencyMap[item] ?? 0) + 1;
    }
    return frequencyMap;
  }
}

Example Usage

void main() {
  List<String> items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
  var frequencyMap = items.countFrequency();

  print(frequencyMap); // Output: {apple: 3, banana: 2, orange: 1}
}

If you agree, I can open a PR with code and tests for all Iterable subclasses including Edge Cases.

pvlKryu commented 3 months ago

I've opened https://github.com/dart-lang/collection/pull/357 PR for this issue.