insertInOrderString function

String insertInOrderString(
  1. String sub,
  2. String original
)

Insert a character before the first greater character

Implementation

String insertInOrderString(String sub, String original) {
  if (sub.isEmpty) {
    return original;
  }
  if (original.isEmpty) {
    return sub;
  }

  List<int> originalCodes = original.codeUnits;
  List<int> subCodes = sub.codeUnits;
  if (subCodes.first <= originalCodes.first) {
    return String.fromCharCodes(subCodes + originalCodes);
  }

  for (int code in original.codeUnits) {
    if (code >= subCodes.first) {
      int index = originalCodes.indexOf(code);
      return String.fromCharCodes(originalCodes.sublist(0, index) +
          subCodes +
          originalCodes.sublist(index));
    }
  }

  return String.fromCharCodes(originalCodes + subCodes);
}