Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
pvlKryu opened this issue Jul 27, 2024 · 1 comment

Comments

@pvlKryu
Copy link

pvlKryu commented Jul 27, 2024

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
Copy link
Author

pvlKryu commented Aug 2, 2024

I've opened dart-archive/collection#357 PR for this issue.

@mosuem mosuem transferred this issue from dart-archive/collection Oct 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants