index.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function isUppercase(char = "") {
  2. return char.toUpperCase() === char;
  3. }
  4. const STR_SPLITTERS = ["-", "_", "/", "."];
  5. function splitByCase(str, splitters = STR_SPLITTERS) {
  6. const parts = [];
  7. let buff = "";
  8. let previusUpper = isUppercase(str[0]);
  9. let previousSplitter = splitters.includes(str[0]);
  10. for (const char of str.split("")) {
  11. const isSplitter = splitters.includes(char);
  12. if (isSplitter) {
  13. parts.push(buff);
  14. buff = "";
  15. previusUpper = false;
  16. previousSplitter = true;
  17. } else if (!previousSplitter && !previusUpper && isUppercase(char)) {
  18. parts.push(buff);
  19. buff = char;
  20. previusUpper = true;
  21. previousSplitter = false;
  22. } else {
  23. buff += char;
  24. previusUpper = isUppercase(char);
  25. previousSplitter = isSplitter;
  26. }
  27. }
  28. if (buff) {
  29. parts.push(buff);
  30. }
  31. return parts;
  32. }
  33. function upperFirst(str) {
  34. if (!str) {
  35. return "";
  36. }
  37. return str[0].toUpperCase() + str.substr(1);
  38. }
  39. function lowerFirst(str) {
  40. if (!str) {
  41. return "";
  42. }
  43. return str[0].toLocaleLowerCase() + str.substr(1);
  44. }
  45. function pascalCase(str = "") {
  46. return (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(p)).join("");
  47. }
  48. function camelCase(str = "") {
  49. return lowerFirst(pascalCase(str));
  50. }
  51. function kebabCase(str = "", joiner = "-") {
  52. return (Array.isArray(str) ? str : splitByCase(str)).map((p = "") => p.toLocaleLowerCase()).join(joiner);
  53. }
  54. function snakeCase(str = "") {
  55. return kebabCase(str, "_");
  56. }
  57. export { camelCase, isUppercase, kebabCase, lowerFirst, pascalCase, snakeCase, splitByCase, upperFirst };