Skip to content

Commit

Permalink
feat: add comments to number literal
Browse files Browse the repository at this point in the history
  • Loading branch information
pionxzh committed Aug 21, 2023
1 parent 906ee1d commit b65a4ee
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 19 deletions.
7 changes: 4 additions & 3 deletions packages/unminify/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,19 @@ Reverse: [babel-plugin-minify-infinity](https://babeljs.io/docs/babel-plugin-min

### `un-number-literal`
Transform number literal to its decimal representation.\
A comment will be added to the end of the line to indicate the original representation.\
Reverse: [babel-plugin-minify-numeric-literals](https://babeljs.io/docs/babel-plugin-minify-numeric-literals)


```diff
- 1e3
+ 1000
+ 1000 /* 1e3 */

- 0b101010
+ 42
+ 42 /* 0b101010 */

- 0x123
+ 291
+ 291 /* 0x123 */
```

### `un-sequence-expression`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,34 @@ import { defineInlineTest } from './test-utils'

const inlineTest = defineInlineTest(transform)

inlineTest('transform number literal exponential notation',
inlineTest('transform number literal with different notation',
`
65536
123.4
0b101010
0o777
-0x123
4.2e2
-2e4
65536;
123.4;
0b101010;
0o777;
-0x123;
4.2e2;
-2e4;
`,
`
65536
123.4
42
511
-291
420
-20000
65536;
123.4;
42/* 0b101010 */;
511/* 0o777 */;
-291/* -0x123 */;
420/* 4.2e2 */;
-20000/* -2e4 */;
`,
)

inlineTest('transform number literal with comment',
`
// comment
0b101010;
`,
`
// comment
42/* 0b101010 */;
`,
)
11 changes: 10 additions & 1 deletion packages/unminify/src/transformations/un-number-literal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { NumericLiteral } from 'jscodeshift'

/**
* Transform number literal to its decimal representation.
* A comment will be added to the end of the line to indicate the original representation.
*
* Including:
* - Decimal (Base 10)
Expand Down Expand Up @@ -32,7 +33,15 @@ export const transformAST: ASTTransformation = (context) => {
if (typeof value !== 'number') return

if (raw && raw !== value.toString()) {
path.replace(j.numericLiteral(value))
const originalComment = path.node.comments || []
console.log(path.parent.node.type)
const operator = j.UnaryExpression.check(path.parent.node) && path.parent.node.operator === '-'
? '-'
: ''
const comment = j.commentBlock(` ${operator}${raw} `, false, true)
const decimalRepresentation = j.numericLiteral(value)
decimalRepresentation.comments = [...originalComment, comment]
path.replace(decimalRepresentation)
}
})
}
Expand Down

0 comments on commit b65a4ee

Please sign in to comment.