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:
parent
2d35f5a8f7
commit
fdb5829a60
@ -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]+/, "");
|
||||
|
||||
@ -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 () {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user