Skip to content

Instantly share code, notes, and snippets.

@ralflorent
Last active March 25, 2021 12:42
Show Gist options
  • Save ralflorent/8a4adf3236e0246dac500a4eaf0f74cb to your computer and use it in GitHub Desktop.
Save ralflorent/8a4adf3236e0246dac500a4eaf0f74cb to your computer and use it in GitHub Desktop.
Summarizer: a simple example of how to use the basics of mixins in Dart.
void main() {
var n = Name('Harry Potter');
print(n.distribution);
var s = Summary('abracadabra');
print(s.distribution);
}
/// Sample example.
class Name with Summarizer {
final String name;
Name(this.name) {
super.compute(name);
}
}
/// Summary of descriptive (categorical) statistics of name components.
class Summary with Summarizer {
Summary(String namon, {List<String>? restrictions}) {
super.compute(namon, restrictions: restrictions);
}
}
/// A component that knows how to help a class extend some basic categorical
/// statistics on string values.
/// Extracted from the `namefully` package available at: https://pub.dev/packages/namefully
mixin Summarizer {
Map<String, int> _distribution = {};
int _count = 0;
int _frequency = 0;
String _top = '';
int _unique = 0;
late final String _string;
late final List<String> _restrictions;
/// The characters' distribution along with their frequencies.
Map<String, int> get distribution => _distribution;
/// The number of characters of the distribution, excluding the restricted
/// ones.
int get count => _count;
/// The total number of characters of the content.
int get length => _string.length;
/// The count of the most repeated characters.
int get frequency => _frequency;
/// The most repeated character.
String get top => _top;
/// The count of unique characters
int get unique => _unique;
/// Creates a summary of a given string of alphabetical characters.
Summarizer compute(String string, {List<String>? restrictions}) {
_string = string;
_restrictions = restrictions ?? const [' '];
if (string.isEmpty || string.length < 2) {
throw ArgumentError('non-empty string value');
}
_distribution = _groupByChar();
_unique = _distribution.keys.length;
_count = _distribution.values.reduce((acc, val) => acc + val);
for (var entry in _distribution.entries) {
if (entry.value >= _frequency) {
_frequency = entry.value;
_top = entry.key;
}
}
return this;
}
/// Creates the distribution, taking the restricted characters into account.
Map<String, int> _groupByChar() {
final frequencies = <String, int>{};
var restrictions = _restrictions.map((n) => n.toUpperCase());
for (var char in _string.toUpperCase().split('')) {
if (restrictions.contains(char)) continue;
if (frequencies.containsKey(char)) {
frequencies[char] = frequencies[char]! + 1;
} else {
frequencies[char] = 1;
}
}
return frequencies;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment