Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

80 linhas
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. if s == "" {
  32. return s
  33. }
  34. if a, ok := uppercaseAcronym[s]; ok {
  35. s = a
  36. }
  37. n := strings.Builder{}
  38. n.Grow(len(s))
  39. capNext := initCase
  40. for i, v := range []byte(s) {
  41. vIsCap := v >= 'A' && v <= 'Z'
  42. vIsLow := v >= 'a' && v <= 'z'
  43. if capNext {
  44. if vIsLow {
  45. v += 'A'
  46. v -= 'a'
  47. }
  48. } else if i == 0 {
  49. if vIsCap {
  50. v += 'a'
  51. v -= 'A'
  52. }
  53. }
  54. if vIsCap || vIsLow {
  55. n.WriteByte(v)
  56. capNext = false
  57. } else if vIsNum := v >= '0' && v <= '9'; vIsNum {
  58. n.WriteByte(v)
  59. capNext = true
  60. } else {
  61. capNext = v == '_' || v == ' ' || v == '-' || v == '.'
  62. }
  63. }
  64. return n.String()
  65. }
  66. // ToCamel converts a string to CamelCase
  67. func ToCamel(s string) string {
  68. return toCamelInitCase(s, true)
  69. }
  70. // ToLowerCamel converts a string to lowerCamelCase
  71. func ToLowerCamel(s string) string {
  72. return toCamelInitCase(s, false)
  73. }