index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const preserveCamelCase = string => {
  3. let isLastCharLower = false;
  4. let isLastCharUpper = false;
  5. let isLastLastCharUpper = false;
  6. for (let i = 0; i < string.length; i++) {
  7. const character = string[i];
  8. if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
  9. string = string.slice(0, i) + '-' + string.slice(i);
  10. isLastCharLower = false;
  11. isLastLastCharUpper = isLastCharUpper;
  12. isLastCharUpper = true;
  13. i++;
  14. } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
  15. string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
  16. isLastLastCharUpper = isLastCharUpper;
  17. isLastCharUpper = false;
  18. isLastCharLower = true;
  19. } else {
  20. isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
  21. isLastLastCharUpper = isLastCharUpper;
  22. isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
  23. }
  24. }
  25. return string;
  26. };
  27. const camelCase = (input, options) => {
  28. if (!(typeof input === 'string' || Array.isArray(input))) {
  29. throw new TypeError('Expected the input to be `string | string[]`');
  30. }
  31. options = Object.assign({
  32. pascalCase: false
  33. }, options);
  34. const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
  35. if (Array.isArray(input)) {
  36. input = input.map(x => x.trim())
  37. .filter(x => x.length)
  38. .join('-');
  39. } else {
  40. input = input.trim();
  41. }
  42. if (input.length === 0) {
  43. return '';
  44. }
  45. if (input.length === 1) {
  46. return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
  47. }
  48. const hasUpperCase = input !== input.toLowerCase();
  49. if (hasUpperCase) {
  50. input = preserveCamelCase(input);
  51. }
  52. input = input
  53. .replace(/^[_.\- ]+/, '')
  54. .toLowerCase()
  55. .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase())
  56. .replace(/\d+(\w|$)/g, m => m.toUpperCase());
  57. return postProcess(input);
  58. };
  59. module.exports = camelCase;
  60. // TODO: Remove this for the next major release
  61. module.exports.default = camelCase;