foldText function

String foldText(
  1. String text
)

Lowercases text and strips the diacritics the Latin alphabet writes with, so that Crème folds to creme and sorts next to cream.

Used by case-insensitive sorting, filtering and search. It covers Latin-1 Supplement and Latin Extended-A, which is what European data arrives in; it is deliberately not a full Unicode collation, which would need tables this package will not carry.

Implementation

String foldText(String text) {
  // Text that is already lower-case ASCII folds to itself, and that is the
  // overwhelmingly common case: it is returned unchanged, without the scan
  // and the copy `toLowerCase` would make. A sort that folds a key per row
  // depends on this being free when there is nothing to do.
  var needsWork = false;
  for (var i = 0; i < text.length; i++) {
    final unit = text.codeUnitAt(i);
    if ((unit >= 0x41 && unit <= 0x5A) || unit > 0x7F) {
      needsWork = true;
      break;
    }
  }
  if (!needsWork) return text;

  final lower = text.toLowerCase();
  var needsFolding = false;
  for (var i = 0; i < lower.length; i++) {
    if (lower.codeUnitAt(i) > 0x7F) {
      needsFolding = true;
      break;
    }
  }
  if (!needsFolding) return lower;

  final out = StringBuffer();
  for (var i = 0; i < lower.length; i++) {
    final unit = lower.codeUnitAt(i);
    if (unit <= 0x7F) {
      out.writeCharCode(unit);
      continue;
    }
    final folded = _diacritics[unit];
    if (folded == null) {
      out.writeCharCode(unit);
    } else {
      out.write(folded);
    }
  }
  return out.toString();
}