index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @typedef Options
  3. * Configuration.
  4. * @property {boolean | null | undefined} [jsx=false]
  5. * Support JSX identifiers (default: `false`).
  6. */
  7. const startRe = /[$_\p{ID_Start}]/u
  8. const contRe = /[$_\u{200C}\u{200D}\p{ID_Continue}]/u
  9. const contReJsx = /[-$_\u{200C}\u{200D}\p{ID_Continue}]/u
  10. const nameRe = /^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u
  11. const nameReJsx = /^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u
  12. /** @type {Options} */
  13. const emptyOptions = {}
  14. /**
  15. * Checks if the given code point can start an identifier.
  16. *
  17. * @param {number | undefined} code
  18. * Code point to check.
  19. * @returns {boolean}
  20. * Whether `code` can start an identifier.
  21. */
  22. // Note: `undefined` is supported so you can pass the result from `''.codePointAt`.
  23. export function start(code) {
  24. return code ? startRe.test(String.fromCodePoint(code)) : false
  25. }
  26. /**
  27. * Checks if the given code point can continue an identifier.
  28. *
  29. * @param {number | undefined} code
  30. * Code point to check.
  31. * @param {Options | null | undefined} [options]
  32. * Configuration (optional).
  33. * @returns {boolean}
  34. * Whether `code` can continue an identifier.
  35. */
  36. // Note: `undefined` is supported so you can pass the result from `''.codePointAt`.
  37. export function cont(code, options) {
  38. const settings = options || emptyOptions
  39. const re = settings.jsx ? contReJsx : contRe
  40. return code ? re.test(String.fromCodePoint(code)) : false
  41. }
  42. /**
  43. * Checks if the given value is a valid identifier name.
  44. *
  45. * @param {string} name
  46. * Identifier to check.
  47. * @param {Options | null | undefined} [options]
  48. * Configuration (optional).
  49. * @returns {boolean}
  50. * Whether `name` can be an identifier.
  51. */
  52. export function name(name, options) {
  53. const settings = options || emptyOptions
  54. const re = settings.jsx ? nameReJsx : nameRe
  55. return re.test(name)
  56. }