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.

81 lines
2.1 KiB

  1. /*
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2015 Ian Coleman
  5. * Copyright (c) 2018 Ma_124, <github.com/Ma124>
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, Subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or Substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. */
  25. package strcase
  26. import (
  27. "strings"
  28. )
  29. // Converts a string to CamelCase
  30. func toCamelInitCase(s string, initCase bool) string {
  31. s = strings.TrimSpace(s)
  32. if s == "" {
  33. return s
  34. }
  35. if a, ok := uppercaseAcronym[s]; ok {
  36. s = a
  37. }
  38. n := strings.Builder{}
  39. n.Grow(len(s))
  40. capNext := initCase
  41. for i, v := range []byte(s) {
  42. vIsCap := v >= 'A' && v <= 'Z'
  43. vIsLow := v >= 'a' && v <= 'z'
  44. if capNext {
  45. if vIsLow {
  46. v += 'A'
  47. v -= 'a'
  48. }
  49. } else if i == 0 {
  50. if vIsCap {
  51. v += 'a'
  52. v -= 'A'
  53. }
  54. }
  55. if vIsCap || vIsLow {
  56. n.WriteByte(v)
  57. capNext = false
  58. } else if vIsNum := v >= '0' && v <= '9'; vIsNum {
  59. n.WriteByte(v)
  60. capNext = true
  61. } else {
  62. capNext = v == '_' || v == ' ' || v == '-' || v == '.'
  63. }
  64. }
  65. return n.String()
  66. }
  67. // ToCamel converts a string to CamelCase
  68. func ToCamel(s string) string {
  69. return toCamelInitCase(s, true)
  70. }
  71. // ToLowerCamel converts a string to lowerCamelCase
  72. func ToLowerCamel(s string) string {
  73. return toCamelInitCase(s, false)
  74. }