getFrequency static method

String getFrequency(
  1. {required AppModel appModel,
  2. required DictionaryHeading heading,
  3. required SortingMethod sortBy,
  4. required bool useMinInDictionary}
)

Returns the frequency, set useMinInDictionary to true to only use the lower value if one dictionary provides multiple values.

Implementation

static String getFrequency({
  required AppModel appModel,
  required DictionaryHeading heading,
  required SortingMethod sortBy,
  required bool useMinInDictionary,
}) {
  List<Dictionary> dictionaries = appModel.dictionaries;

  List<String> unhiddenDictionaries = dictionaries
      .where((d) => !d.isHidden(appModel.targetLanguage))
      .map((d) => d.name)
      .toList();

  List<(double, String)> unhiddenFrequencies = heading.frequencies
      .where((entry) =>
          unhiddenDictionaries.contains(entry.dictionary.value!.name))
      .map((freq) => (freq.value, freq.dictionary.value!.name))
      .toList();

  List<double> frequencies = useMinInDictionary
      ? []
      : unhiddenFrequencies.map((tup) => tup.$1).toList();

  if (useMinInDictionary) {
    Map<String, double> dictionariesPlusFreq = {};
    for (var tup in unhiddenFrequencies) {
      var entry = dictionariesPlusFreq[tup.$2];
      dictionariesPlusFreq[tup.$2] =
          entry == null ? tup.$1 : min(entry, tup.$1);
    }
    frequencies = dictionariesPlusFreq.values.toList();
  }

  unhiddenFrequencies.map((tup) => tup.$1).toList();

  if (frequencies.isEmpty) {
    return '';
  }

  double ret;

  switch (sortBy) {
    case SortingMethod.harmonic:
      ret = frequencies.length /
          frequencies.fold(0, (prev, freq) => (1 / freq) + prev);
      break;
    case SortingMethod.min:
      ret = frequencies.reduce((f1, f2) => f1 < f2 ? f1 : f2);
      break;
    case SortingMethod.avg:
      ret = frequencies.fold(0, (prev, freq) => prev + freq.toInt()) /
          frequencies.length;
      break;
  }

  return ret.round().toString();
}