dvMinifyJs function
js without its comments and without the indentation, and with every
line it had.
Lines are never joined. JavaScript inserts semicolons at newlines, so
const a = 1 followed by const b = 2 is two statements on two lines and
one syntax error on one. Nothing inside a string, a template literal or a
regular expression is touched.
Implementation
String dvMinifyJs(String js) {
final StringBuffer out = StringBuffer();
bool space = false;
bool newline = false;
// What was written last decides whether the next `/` opens a regular
// expression or divides: `return /x/` is a pattern, `a / x` is division.
String previous = '';
void flush() {
if (out.isEmpty) return;
if (newline) {
out.write('\n');
} else if (space) {
out.write(' ');
}
space = false;
newline = false;
}
void write(String text) {
flush();
out.write(text);
previous = text.trimRight();
space = false;
newline = false;
}
for (int i = 0; i < js.length; i++) {
final String c = js[i];
if (c == '/' && i + 1 < js.length && js[i + 1] == '/') {
final int end = js.indexOf('\n', i);
i = end < 0 ? js.length : end - 1;
space = true;
continue;
}
if (c == '/' && i + 1 < js.length && js[i + 1] == '*') {
final int end = js.indexOf('*/', i + 2);
final String comment = js.substring(i, end < 0 ? js.length : end + 2);
if (comment.contains('\n')) newline = true;
space = true;
i = end < 0 ? js.length : end + 1;
continue;
}
if (c == '\n') {
newline = true;
space = true;
continue;
}
if (_isSpace(c)) {
space = true;
continue;
}
if (c == '"' || c == "'") {
final int end = _stringEnd(js, i, c);
write(js.substring(i, end));
i = end - 1;
continue;
}
if (c == '`') {
final int end = _templateEnd(js, i);
write(js.substring(i, end));
i = end - 1;
continue;
}
if (c == '/' && _regexCanStart(previous)) {
final int end = _regexEnd(js, i);
write(js.substring(i, end));
i = end - 1;
continue;
}
write(c);
}
return out.toString();
}