Make SerializeVisitor._removeExponent work with non-exponent numbers

This allows us to avoid traversing the number string more times than
necessary.
This commit is contained in:
Natalie Weizenbaum 2019-05-20 14:30:47 -07:00
parent db87ed2f0e
commit 5b9835a5bd

View File

@ -689,23 +689,37 @@ class _SerializeVisitor implements CssVisitor, ValueVisitor, SelectorVisitor {
_writeDecimal(text); _writeDecimal(text);
} }
/// Assuming [text] is a double written in exponent notation, returns a string /// If [text] is written in exponent notation, returns a string representation
/// representation of that double without exponent notation. /// of it without exponent notation.
///
/// Otherwise, returns [text] as-is.
String _removeExponent(String text) { String _removeExponent(String text) {
var buffer = StringBuffer(); // Don't allocate this until we know [text] contains exponent notation.
StringBuffer buffer;
int exponent; int exponent;
for (var i = 0; i < text.length; i++) { for (var i = 0; i < text.length; i++) {
var codeUnit = text.codeUnitAt(i); var codeUnit = text.codeUnitAt(i);
if (codeUnit == $e) { if (codeUnit != $e) continue;
exponent = int.parse(text.substring(i + 1, text.length));
break; buffer = StringBuffer();
} else if (codeUnit != $dot) { buffer.writeCharCode(text.codeUnitAt(0));
buffer.writeCharCode(codeUnit);
} // If the number has more than one significant digit, the second
// character will be a decimal point that we don't want to include in
// the generated number.
if (i > 2) buffer.write(text.substring(2, i));
exponent = int.parse(text.substring(i + 1, text.length));
break;
} }
if (buffer == null) return text;
if (exponent > 0) { if (exponent > 0) {
for (var i = 0; i < exponent; i++) { // Write an additional zero for each exponent digits other than those
// already written to the buffer. We subtract 1 from `buffer.length`
// because the first digit doesn't count towards the exponent.
var additionalZeroes = exponent - (buffer.length - 1);
for (var i = 0; i < additionalZeroes; i++) {
buffer.writeCharCode($0); buffer.writeCharCode($0);
} }
return buffer.toString(); return buffer.toString();