Skip to content

Commit

Permalink
Cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Apr 4, 2020
1 parent 257a70d commit 90f7826
Showing 1 changed file with 8 additions and 19 deletions.
27 changes: 8 additions & 19 deletions packages/babel-plugin-transform-unicode-escapes/src/index.js
Expand Up @@ -10,9 +10,9 @@ export default declare(api => {
function escape(code) {
return "\\u" + code.toString(16).padStart(4, 0);
}
function replaceUnicodeEscapes(str, escapeCount = 1) {
function replaceUnicodeEscapes(str) {
return str.replace(unicodeEscape, (match, backslashes, code) => {
if ((backslashes.length * escapeCount) % 2 === 0) {
if (backslashes.length % 2 === 0) {
return match;
}

Expand All @@ -29,17 +29,13 @@ export default declare(api => {
Identifier(path) {
const { node, key } = path;
const { name } = node;
const replaced = name.replace(surrogate, c => {
c = c
.charCodeAt(0)
.toString(16)
.padStart(4);
return `\\u${c}`;
});
const replaced = name.replace(surrogate, escape);
if (name === replaced) return;

const str = t.inherits(t.stringLiteral(name), node);

if (key === "key") {
path.replaceWith(t.stringLiteral(name));
path.replaceWith(str);
return;
}

Expand All @@ -49,7 +45,7 @@ export default declare(api => {
parentPath.isOptionalMemberExpression({ property: node })
) {
parentPath.node.computed = true;
path.replaceWith(t.stringLiteral(name));
path.replaceWith(str);
return;
}

Expand All @@ -62,14 +58,7 @@ export default declare(api => {
const { node } = path;
const { extra } = node;

// A string's value is already parsed, which means a "\u{0061}" is
// already an "a", and a "\\u{0061}` is an "\u{0061}". So we don't want
// to find a "\u" in the value (because dev escaped the "u" and didn't
// write a unicode escape).
node.value = replaceUnicodeEscapes(node.value, 2);
if (extra?.raw) {
extra.raw = replaceUnicodeEscapes(extra.raw);
}
if (extra?.raw) extra.raw = replaceUnicodeEscapes(extra.raw);
},

TemplateElement(path) {
Expand Down

0 comments on commit 90f7826

Please sign in to comment.