版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

78 lines
2.2 KiB

  1. 'use strict';
  2. const NUMBER_CHAR_RE = /\d/;
  3. const STR_SPLITTERS = ["-", "_", "/", "."];
  4. function isUppercase(char = "") {
  5. if (NUMBER_CHAR_RE.test(char)) {
  6. return void 0;
  7. }
  8. return char.toUpperCase() === char;
  9. }
  10. function splitByCase(string_, separators) {
  11. const splitters = separators ?? STR_SPLITTERS;
  12. const parts = [];
  13. if (!string_ || typeof string_ !== "string") {
  14. return parts;
  15. }
  16. let buff = "";
  17. let previousUpper;
  18. let previousSplitter;
  19. for (const char of string_) {
  20. const isSplitter = splitters.includes(char);
  21. if (isSplitter === true) {
  22. parts.push(buff);
  23. buff = "";
  24. previousUpper = void 0;
  25. continue;
  26. }
  27. const isUpper = isUppercase(char);
  28. if (previousSplitter === false) {
  29. if (previousUpper === false && isUpper === true) {
  30. parts.push(buff);
  31. buff = char;
  32. previousUpper = isUpper;
  33. continue;
  34. }
  35. if (previousUpper === true && isUpper === false && buff.length > 1) {
  36. const lastChar = buff[buff.length - 1];
  37. parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
  38. buff = lastChar + char;
  39. previousUpper = isUpper;
  40. continue;
  41. }
  42. }
  43. buff += char;
  44. previousUpper = isUpper;
  45. previousSplitter = isSplitter;
  46. }
  47. parts.push(buff);
  48. return parts;
  49. }
  50. function upperFirst(string_) {
  51. return !string_ ? "" : string_[0].toUpperCase() + string_.slice(1);
  52. }
  53. function lowerFirst(string_) {
  54. return !string_ ? "" : string_[0].toLowerCase() + string_.slice(1);
  55. }
  56. function pascalCase(string_) {
  57. return !string_ ? "" : (Array.isArray(string_) ? string_ : splitByCase(string_)).map((p) => upperFirst(p)).join("");
  58. }
  59. function camelCase(string_) {
  60. return lowerFirst(pascalCase(string_));
  61. }
  62. function kebabCase(string_, joiner) {
  63. return !string_ ? "" : (Array.isArray(string_) ? string_ : splitByCase(string_)).map((p) => p.toLowerCase()).join(joiner ?? "-");
  64. }
  65. function snakeCase(string_) {
  66. return kebabCase(string_, "_");
  67. }
  68. exports.camelCase = camelCase;
  69. exports.isUppercase = isUppercase;
  70. exports.kebabCase = kebabCase;
  71. exports.lowerFirst = lowerFirst;
  72. exports.pascalCase = pascalCase;
  73. exports.snakeCase = snakeCase;
  74. exports.splitByCase = splitByCase;
  75. exports.upperFirst = upperFirst;