Debian Codegraph @

packages/babel-types/src/converters/toIdentifier.ts

raw
1 import isValidIdentifier from "../validators/isValidIdentifier";
2 import { isIdentifierChar } from "@babel/helper-validator-identifier";
3
4 export default function toIdentifier(input: string): string {
5 input = input + "";
6
7 // replace all non-valid identifiers with dashes
8 let name = "";
9 for (const c of input) {
10 name += isIdentifierChar(c.codePointAt(0)) ? c : "-";
11 }
12
13 // remove all dashes and numbers from start of name
14 name = name.replace(/^[-0-9]+/, "");
15
16 // camel case
17 name = name.replace(/[-\s]+(.)?/g, function (match, c) {
18 return c ? c.toUpperCase() : "";
19 });
20
21 if (!isValidIdentifier(name)) {
22 name = `_${name}`;
23 }
24
25 return name || "_";
26 }