casing.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const assert = require('assert')
  2. const invalidChars = /[^a-zA-Z0-9:]+/g
  3. /**
  4. * Convert text to kebab-case
  5. * @param {string} str Text to be converted
  6. * @return {string}
  7. */
  8. function kebabCase (str) {
  9. return str
  10. .replace(/[A-Z]/g, match => '-' + match)
  11. .replace(/([^a-zA-Z])-([A-Z])/g, match => match[0] + match[2])
  12. .replace(/^-/, '')
  13. .replace(invalidChars, '-')
  14. .toLowerCase()
  15. }
  16. /**
  17. * Convert text to snake_case
  18. * @param {string} str Text to be converted
  19. * @return {string}
  20. */
  21. function snakeCase (str) {
  22. return str
  23. .replace(/[A-Z]/g, match => '_' + match)
  24. .replace(/([^a-zA-Z])_([A-Z])/g, match => match[0] + match[2])
  25. .replace(/^_/, '')
  26. .replace(invalidChars, '_')
  27. .toLowerCase()
  28. }
  29. /**
  30. * Convert text to camelCase
  31. * @param {string} str Text to be converted
  32. * @return {string} Converted string
  33. */
  34. function camelCase (str) {
  35. return str
  36. .replace(/_/g, (_, index) => index === 0 ? _ : '-')
  37. .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) =>
  38. index === 0 ? letter.toLowerCase() : letter.toUpperCase()
  39. )
  40. .replace(invalidChars, '')
  41. }
  42. /**
  43. * Convert text to PascalCase
  44. * @param {string} str Text to be converted
  45. * @return {string} Converted string
  46. */
  47. function pascalCase (str) {
  48. return str
  49. .replace(/_/g, (_, index) => index === 0 ? _ : '-')
  50. .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => letter.toUpperCase())
  51. .replace(invalidChars, '')
  52. }
  53. const convertersMap = {
  54. 'kebab-case': kebabCase,
  55. 'snake_case': snakeCase,
  56. 'camelCase': camelCase,
  57. 'PascalCase': pascalCase
  58. }
  59. module.exports = {
  60. allowedCaseOptions: [
  61. 'camelCase',
  62. 'kebab-case',
  63. 'PascalCase'
  64. ],
  65. /**
  66. * Return case converter
  67. * @param {string} name type of converter to return ('camelCase', 'kebab-case', 'PascalCase')
  68. * @return {kebabCase|camelCase|pascalCase}
  69. */
  70. getConverter (name) {
  71. assert(typeof name === 'string')
  72. return convertersMap[name] || pascalCase
  73. },
  74. camelCase,
  75. pascalCase,
  76. kebabCase,
  77. snakeCase
  78. }