eat method
Consumes characters that match a test function and returns their range.
If length is null, consumes characters while test returns true,
stopping at the first failing character or end of input. The test function
receives each character and its 0-based index from the match start.
If length is specified, consumes exactly that many characters if they
all pass the test. If any character fails, returns null and resets position.
Returns a record with (startIndex, endIndex) of consumed characters, or null if no characters matched.
Example:
// Consume all digits
final range = eat((char, _) => char.codeUnitAt(0) >= '0'.codeUnitAt(0) &&
char.codeUnitAt(0) <= '9'.codeUnitAt(0), null);
Implementation
({int startIndex, int endIndex})? eat(
bool Function(String char, int index) test,
int? length,
) {
if (length == null) {
int startIndex = index;
while (index < endIndex && test(source[index], index - startIndex)) {
index++;
}
if (startIndex == index) {
return null;
}
return (startIndex: startIndex, endIndex: index);
}
int startIndex = index;
for (int i = 0; i < length; i++) {
if (index >= endIndex || !test(source[index], i)) {
index = startIndex;
return null;
}
index++;
}
return (startIndex: startIndex, endIndex: index);
}