string-utils.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export function camelCase(str) {
  2. // Handle the case where an argument is provided as camel case, e.g., fooBar.
  3. // by ensuring that the string isn't already mixed case:
  4. const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  5. if (!isCamelCase) {
  6. str = str.toLocaleLowerCase();
  7. }
  8. if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
  9. return str;
  10. }
  11. else {
  12. let camelcase = '';
  13. let nextChrUpper = false;
  14. const leadingHyphens = str.match(/^-+/);
  15. for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
  16. let chr = str.charAt(i);
  17. if (nextChrUpper) {
  18. nextChrUpper = false;
  19. chr = chr.toLocaleUpperCase();
  20. }
  21. if (i !== 0 && (chr === '-' || chr === '_')) {
  22. nextChrUpper = true;
  23. }
  24. else if (chr !== '-' && chr !== '_') {
  25. camelcase += chr;
  26. }
  27. }
  28. return camelcase;
  29. }
  30. }
  31. export function decamelize(str, joinString) {
  32. const lowercase = str.toLocaleLowerCase();
  33. joinString = joinString || '-';
  34. let notCamelcase = '';
  35. for (let i = 0; i < str.length; i++) {
  36. const chrLower = lowercase.charAt(i);
  37. const chrString = str.charAt(i);
  38. if (chrLower !== chrString && i > 0) {
  39. notCamelcase += `${joinString}${lowercase.charAt(i)}`;
  40. }
  41. else {
  42. notCamelcase += chrString;
  43. }
  44. }
  45. return notCamelcase;
  46. }
  47. export function looksLikeNumber(x) {
  48. if (x === null || x === undefined)
  49. return false;
  50. // if loaded from config, may already be a number.
  51. if (typeof x === 'number')
  52. return true;
  53. // hexadecimal.
  54. if (/^0x[0-9a-f]+$/i.test(x))
  55. return true;
  56. // don't treat 0123 as a number; as it drops the leading '0'.
  57. if (x.length > 1 && x[0] === '0')
  58. return false;
  59. return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  60. }