Use isIdentifierChar instead of regex for toIdentifier (#12575)

* 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>
This commit is contained in:
Niklas Mischkulnig 2020-12-31 17:22:46 +01:00 committed by GitHub
parent 2d35f5a8f7
commit fdb5829a60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 3 deletions

View File

@ -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]+/, "");

View File

@ -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 () {