split method

List<DVTextChunk> split(
  1. String text
)

Implementation

List<DVTextChunk> split(String text) {
  if (maxCharacters < 1) {
    throw ArgumentError.value(maxCharacters, 'maxCharacters', 'must be positive');
  }
  if (overlap < 0 || overlap >= maxCharacters) {
    throw ArgumentError.value(
        overlap, 'overlap', 'must be at least 0 and below maxCharacters');
  }
  if (text.isEmpty) return const <DVTextChunk>[];
  if (text.length <= maxCharacters) return <DVTextChunk>[DVTextChunk(0, text)];

  final List<DVTextChunk> chunks = <DVTextChunk>[];
  int start = 0;
  while (start < text.length) {
    int end = math.min(start + maxCharacters, text.length);
    if (end < text.length) {
      // Break on whitespace when there is some in the back half, so a chunk
      // does not end in the middle of a word it then fails to match.
      final int space = text.lastIndexOf(RegExp(r'\s'), end);
      if (space > start + maxCharacters ~/ 2) end = space;
    }
    chunks.add(DVTextChunk(start, text.substring(start, end)));
    if (end >= text.length) break;
    start = math.max(end - overlap, start + 1);
  }
  return chunks;
}