Skip to content

Commit

Permalink
Use isIdentifierChar instead of regex for toIdentifier (#12575)
Browse files Browse the repository at this point in the history
* Use isIdentifierChar instead of regex for toIdentifier

* Apply suggestions from code review

Co-authored-by: Huáng Jùnliàng <jlhwung@gmail.com>

* Undo dep

* Update packages/babel-types/test/converters.js

* Add testcase starting with a number

* Add test for non-ascii starting character

Co-authored-by: Huáng Jùnliàng <jlhwung@gmail.com>
  • Loading branch information
mischnic and JLHwung authored Dec 31, 2020
1 parent 2d35f5a commit fdb5829
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/babel-types/src/converters/toIdentifier.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import isValidIdentifier from "../validators/isValidIdentifier";
import { isIdentifierChar } from "@babel/helper-validator-identifier";

export default function toIdentifier(name: string): string {
name = name + "";
export default function toIdentifier(input: string): string {
input = input + "";

// replace all non-valid identifiers with dashes
name = name.replace(/[^a-zA-Z0-9$_]/g, "-");
let name = "";
for (const c of input) {
name += isIdentifierChar(c.codePointAt(0)) ? c : "-";
}

// remove all dashes and numbers from start of name
name = name.replace(/^[-0-9]+/, "");
Expand Down
4 changes: 4 additions & 0 deletions packages/babel-types/test/converters.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ function generateCode(node) {
describe("converters", function () {
it("toIdentifier", function () {
expect(t.toIdentifier("swag-lord")).toBe("swagLord");
expect(t.toIdentifier("ɵ2")).toBe("ɵ2");
expect(t.toIdentifier("ℬ1")).toBe("ℬ1");
expect(t.toIdentifier("1bc")).toBe("bc");
expect(t.toIdentifier("\u0487a")).toBe("_\u0487a");
});

describe("valueToNode", function () {
Expand Down

0 comments on commit fdb5829

Please sign in to comment.