findPattern method Null safety

List<int>? findPattern(
  1. {required String pattern}
)

Given a pattern returns the starting indices of all occurences of the pattern in the string.

Example

String foo = 'abracadabra';
String fooOccs = foo.findPatterns(pattern:'abr'); // returns '[0, 7]'

Implementation

List<int>? findPattern({required String pattern}) {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return [];
  }
  // ignore: omit_local_variable_types
  List<int> occurences = [];
  // How many times the pattern can fit the text provided
  var fitCount = (this!.length / pattern.length).truncate().toInt();

  if (fitCount > this!.length) {
    return [];
  }
  if (fitCount == 1) {
    if (this == pattern) {
      return [0];
    }
    return [];
  }

  for (var i = 0; i <= this!.length; i++) {
    if (i + pattern.length > this!.length) {
      return occurences;
    }
    if (this!.substring(i, i + pattern.length) == pattern) {
      occurences.add(i);
    }
  }

  return occurences;
}