常用类型及数据操作方法
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.

115 lines
2.5 KiB

  1. /*
  2. * string functions
  3. */
  4. package helper
  5. import (
  6. "errors"
  7. "fmt"
  8. "sort"
  9. )
  10. // 求差集
  11. func Diff(slice1, slice2 []string) []string {
  12. m := make(map[string]int)
  13. nn := make([]string, 0)
  14. inter := Intersect(slice1, slice2)
  15. for _, v := range inter {
  16. m[v]++
  17. }
  18. for _, value := range slice1 {
  19. times, _ := m[value]
  20. if times == 0 {
  21. nn = append(nn, value)
  22. }
  23. }
  24. return nn
  25. }
  26. // 求交集
  27. func Intersect(slice1, slice2 []string) []string {
  28. m := make(map[string]int)
  29. nn := make([]string, 0)
  30. for _, v := range slice1 {
  31. m[v]++
  32. }
  33. for _, v := range slice2 {
  34. times, _ := m[v]
  35. if times == 1 {
  36. nn = append(nn, v)
  37. }
  38. }
  39. return nn
  40. }
  41. // 求并集
  42. func Union(slice1, slice2 []string) []string {
  43. m := make(map[string]int)
  44. for _, v := range slice1 {
  45. m[v]++
  46. }
  47. for _, v := range slice2 {
  48. times, _ := m[v]
  49. if times == 0 {
  50. slice1 = append(slice1, v)
  51. }
  52. }
  53. return slice1
  54. }
  55. func Unique(originals interface{}) (interface{}, error) {
  56. temp := map[string]struct{}{}
  57. switch slice := originals.(type) {
  58. case []string:
  59. result := make([]string, 0, len(originals.([]string)))
  60. for _, item := range slice {
  61. key := fmt.Sprint(item)
  62. if _, ok := temp[key]; !ok {
  63. temp[key] = struct{}{}
  64. result = append(result, item)
  65. }
  66. }
  67. return result, nil
  68. case []int64:
  69. result := make([]int64, 0, len(originals.([]int64)))
  70. for _, item := range slice {
  71. key := fmt.Sprint(item)
  72. if _, ok := temp[key]; !ok {
  73. temp[key] = struct{}{}
  74. result = append(result, item)
  75. }
  76. }
  77. return result, nil
  78. default:
  79. return nil, errors.New(fmt.Sprintf("Unknown type: %T", slice))
  80. }
  81. }
  82. // 将切片字符串(数字型)排序
  83. func StringSliceSort(str []string, sort_type string) ([]string, error) {
  84. int_arr := []int{}
  85. string_arr := []string{}
  86. if len(str) < 1 {
  87. return []string{}, nil
  88. }
  89. for _, val := range str {
  90. int_arr = append(int_arr, ToInt(val))
  91. }
  92. if sort_type == "desc" {
  93. sort.Sort(sort.Reverse(sort.IntSlice(int_arr)))
  94. }else{
  95. sort.Ints(int_arr)
  96. }
  97. for _, val_int := range int_arr {
  98. string_arr = append(string_arr, ToStr(val_int))
  99. }
  100. return string_arr, nil
  101. }