flattenMeanings static method

String flattenMeanings(
  1. {required List<DictionaryEntry> entries,
  2. required bool prependDictionaryNames}
)

Get a single combined text for all meanings in a list of entries.

Implementation

static String flattenMeanings({
  required List<DictionaryEntry> entries,
  required bool prependDictionaryNames,
}) {
  StringBuffer meaningBuffer = StringBuffer();

  Map<String, List<DictionaryEntry>> entriesByDictionaryName =
      groupBy<DictionaryEntry, String>(
    entries,
    (entry) => entry.dictionary.value!.name,
  );

  entriesByDictionaryName.forEach((dictionaryName, singleDictionaryEntries) {
    int meaningsCount = 0;
    for (DictionaryEntry entry in singleDictionaryEntries) {
      meaningsCount += entry.definitions.length;
    }

    if (prependDictionaryNames) {
      meaningBuffer.writeln('【$dictionaryName】');
    }

    for (DictionaryEntry entry in singleDictionaryEntries) {
      if (singleDictionaryEntries.length == 1) {
        entry.definitions.forEachIndexed((index, meaning) {
          meaning = meaning.trim();
          if (meaningsCount != 1) {
            meaningBuffer.write('• $meaning');
          } else {
            meaningBuffer.write(meaning);
          }

          if (index != entry.definitions.length - 1) {
            meaningBuffer.write('\n');
          }
        });
      } else {
        entry.definitions.forEachIndexed((index, meaning) {
          meaning = meaning.trim();
          if (meaningsCount == 1) {
            meaningBuffer.write('$meaning\n');
          } else {
            if (index == 0) {
              meaningBuffer.write('• ');
            }
            meaningBuffer.write(meaning);
            if (index != entry.definitions.length - 1) {
              meaningBuffer.write('; ');
            }
          }
        });
      }

      meaningBuffer.write('\n');
    }

    meaningBuffer.write('\n');
  });

  return meaningBuffer.toString().trim();
}