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

88 lines
1.6 KiB

  1. /*
  2. * string functions
  3. */
  4. package helper
  5. import (
  6. "errors"
  7. "fmt"
  8. )
  9. // 求差集
  10. func Diff(slice1, slice2 []string) []string {
  11. m := make(map[string]int)
  12. nn := make([]string, 0)
  13. inter := Intersect(slice1, slice2)
  14. for _, v := range inter {
  15. m[v]++
  16. }
  17. for _, value := range slice1 {
  18. times, _ := m[value]
  19. if times == 0 {
  20. nn = append(nn, value)
  21. }
  22. }
  23. return nn
  24. }
  25. // 求交集
  26. func Intersect(slice1, slice2 []string) []string {
  27. m := make(map[string]int)
  28. nn := make([]string, 0)
  29. for _, v := range slice1 {
  30. m[v]++
  31. }
  32. for _, v := range slice2 {
  33. times, _ := m[v]
  34. if times == 1 {
  35. nn = append(nn, v)
  36. }
  37. }
  38. return nn
  39. }
  40. // 求并集
  41. func Union(slice1, slice2 []string) []string {
  42. m := make(map[string]int)
  43. for _, v := range slice1 {
  44. m[v]++
  45. }
  46. for _, v := range slice2 {
  47. times, _ := m[v]
  48. if times == 0 {
  49. slice1 = append(slice1, v)
  50. }
  51. }
  52. return slice1
  53. }
  54. func Unique(originals interface{}) (interface{}, error) {
  55. temp := map[string]struct{}{}
  56. switch slice := originals.(type) {
  57. case []string:
  58. result := make([]string, 0, len(originals.([]string)))
  59. for _, item := range slice {
  60. key := fmt.Sprint(item)
  61. if _, ok := temp[key]; !ok {
  62. temp[key] = struct{}{}
  63. result = append(result, item)
  64. }
  65. }
  66. return result, nil
  67. case []int64:
  68. result := make([]int64, 0, len(originals.([]int64)))
  69. for _, item := range slice {
  70. key := fmt.Sprint(item)
  71. if _, ok := temp[key]; !ok {
  72. temp[key] = struct{}{}
  73. result = append(result, item)
  74. }
  75. }
  76. return result, nil
  77. default:
  78. return nil, errors.New(fmt.Sprintf("Unknown type: %T", slice))
  79. }
  80. }