commonSuffix method

  1. @useResult
String commonSuffix()

Returns the longest common suffix of all strings in this list.

Returns empty string if list is empty or any element is empty.

Example:

['ending', 'ding'].commonSuffix();  // 'ing'

Implementation

@useResult
String commonSuffix() {
  if (isEmpty) return '';
  String suffix = this[0];
  for (int i = 1; i < length; i++) {
    final String s = this[i];
    final int maxLen = suffix.length < s.length ? suffix.length : s.length;
    int j = 0;
    while (j < maxLen && suffix[suffix.length - 1 - j] == s[s.length - 1 - j]) {
      j++;
    }
    suffix = suffix.replaceRange(0, suffix.length - j, '');
    if (suffix.isEmpty) return '';
  }
  return suffix;
}