Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe("numeric-literals", () => {
expect(transform(source)).toBe(expected);

source = "[1e3, -1e4, 1e-5, 1.5e12, 1.23456, .1];";
expected = "[1e3, -1e4, 1e-5, 1.5e12, 1.23456, .1];";
expected = "[1e3, -1e4, 1e-5, 15e11, 1.23456, .1];";

expect(transform(source)).toBe(expected);

Expand All @@ -32,5 +32,15 @@ describe("numeric-literals", () => {
expected = "[+1e-12, -1e-11];";

expect(transform(source)).toBe(expected);

source = "[666200008e1, 666200008e-1];";
expected = "[6662000080, 66620000.8];";

expect(transform(source)).toBe(expected);

source = "[11000, 66.00000, 6600000, 1.5e-3];";
expected = "[11e3, 66, 66e5, 15e-4];";

expect(transform(source)).toBe(expected);
});
});
35 changes: 23 additions & 12 deletions packages/babel-plugin-minify-numeric-literals/src/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
"use strict";

module.exports = function({ types: t }) {
module.exports = function() {

const transform = (val) => {
const floatVal = parseFloat(val).toString();
const expVal = val.toExponential().replace(/\+/g, "");
if (floatVal.length < expVal.length) {
return floatVal;
}
// 1.1e4 -> 11e3
val = expVal;
if (val.indexOf(".") >= 0 && val.indexOf("e") >= 0) {
const lastChar = val.substr(val.lastIndexOf("e") + 1);
const dotIndex = val.lastIndexOf(".") + 1;
const subLength = val.substr(dotIndex, val.lastIndexOf("e") - dotIndex).length;
val = val.substr(0, val.lastIndexOf("e") + 1) + (lastChar - subLength);
val = val.replace(".", "").replace(/e0/, "");
}
return val;
};

return {
name: "minify-numeric-literals",
visitor: {
NumericLiteral(path) {
if (!path.node.extra) return;

const exponential = path.node.value
.toExponential()
.replace(/\+/g, "")
.replace(/e0/, "");
const newVal = transform(path.node.value);

if (path.node.extra.raw.length > exponential.length) {
const literal = t.numericLiteral(path.node.value);
literal.extra = {
raw: exponential,
rawValue: path.node.value
};
path.replaceWith(literal);
if (path.node.extra.raw.length > newVal.length) {
path.node.extra.raw = newVal;
}
}
}
Expand Down