case.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package misspell
  2. import (
  3. "strings"
  4. )
  5. // WordCase is an enum of various word casing styles
  6. type WordCase int
  7. // Various WordCase types.. likely to be not correct
  8. const (
  9. CaseUnknown WordCase = iota
  10. CaseLower
  11. CaseUpper
  12. CaseTitle
  13. )
  14. // CaseStyle returns what case style a word is in
  15. func CaseStyle(word string) WordCase {
  16. upperCount := 0
  17. lowerCount := 0
  18. // this iterates over RUNES not BYTES
  19. for i := 0; i < len(word); i++ {
  20. ch := word[i]
  21. switch {
  22. case ch >= 'a' && ch <= 'z':
  23. lowerCount++
  24. case ch >= 'A' && ch <= 'Z':
  25. upperCount++
  26. }
  27. }
  28. switch {
  29. case upperCount != 0 && lowerCount == 0:
  30. return CaseUpper
  31. case upperCount == 0 && lowerCount != 0:
  32. return CaseLower
  33. case upperCount == 1 && lowerCount > 0 && word[0] >= 'A' && word[0] <= 'Z':
  34. return CaseTitle
  35. }
  36. return CaseUnknown
  37. }
  38. // CaseVariations returns
  39. // If AllUpper or First-Letter-Only is upcased: add the all upper case version
  40. // If AllLower, add the original, the title and upcase forms
  41. // If Mixed, return the original, and the all upcase form
  42. //
  43. func CaseVariations(word string, style WordCase) []string {
  44. switch style {
  45. case CaseLower:
  46. return []string{word, strings.ToUpper(word[0:1]) + word[1:], strings.ToUpper(word)}
  47. case CaseUpper:
  48. return []string{strings.ToUpper(word)}
  49. default:
  50. return []string{word, strings.ToUpper(word)}
  51. }
  52. }