withoutComments function
code with its comments blanked out, keeping strings as they are and
every character where it was.
Implementation
String withoutComments(String code) {
final StringBuffer out = StringBuffer();
String? quote;
int i = 0;
while (i < code.length) {
final String char = code[i];
if (quote != null) {
out.write(char);
if (char == r'\' && i + 1 < code.length) {
out.write(code[++i]);
} else if (char == quote) {
quote = null;
}
i++;
} else if (char == "'" || char == '"') {
quote = char;
out.write(char);
i++;
} else if (code.startsWith('//', i)) {
while (i < code.length && code[i] != '\n') {
out.write(' ');
i++;
}
} else if (code.startsWith('/*', i)) {
final int close = code.indexOf('*/', i + 2);
final int end = close < 0 ? code.length : close + 2;
out.write(code.substring(i, end).replaceAll(RegExp(r'[^\n]'), ' '));
i = end;
} else {
out.write(char);
i++;
}
}
return out.toString();
}