wordFromIndex method

String wordFromIndex(
  1. {required String text,
  2. required int index}
)

Given an index or a character position in given text, return a word such that it corresponds to a whole word from the parsed list of words from textToWords.

For example, in the case of Japanese, the parameters '日本語は難しいです。' and given index 2 (語), this should be '日本語'.

In the case of English, 'This is a pen.' at index 10 (p), should return the word 'pen'.

Implementation

String wordFromIndex({
  required String text,
  required int index,
}) {
  /// See [indexMaxDistance] above.
  /// If the [indexMaxDistance] is not defined...
  if (indexMaxDistance != null) {
    /// If the length of text cut into two, incrmeented by one exceeds the
    /// [indexMaxDistance] multiplied into two and incremented by one...
    if (((text.length / 2) + 1) > ((indexMaxDistance! * 2) + 1)) {
      /// Then get a substring of text, with the original index character
      /// being the center and to its left and right, a maximum number of
      /// [indexMaxDistance] characters...
      ///
      /// Of course, the indexes of those values will have to be in the range
      /// of (0, length - 1)...
      List<int> originalIndexTape = [];
      List<int> indexTape = [];

      int rangeStart = max(0, index - indexMaxDistance!);
      int rangeEnd = min(text.length - 1, index + indexMaxDistance! + 1);

      for (int i = 0; i < text.length; i++) {
        originalIndexTape.add(i);
      }

      StringBuffer buffer = StringBuffer();
      int newIndex = -1;

      for (int i = 0; i < text.runes.length; i++) {
        if (i >= rangeStart && i < rangeEnd) {
          final String character =
              String.fromCharCode(text.runes.elementAt(i));
          buffer.write(character);

          indexTape.add(i);
          if (index == i) {
            newIndex = indexTape.indexOf(i);
          }
        }
      }

      final String newText = buffer.toString();

      return wordFromIndex(text: newText, index: newIndex);
    }
  }

  List<String> words = textToWords(text);

  List<String> wordTape = [];
  for (int i = 0; i < words.length; i++) {
    String word = words[i];
    for (int j = 0; j < word.length; j++) {
      wordTape.add(word);
    }
  }

  String word = wordTape[index];

  return word;
}