mutations.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package objx
  2. // Exclude returns a new Map with the keys in the specified []string
  3. // excluded.
  4. func (m Map) Exclude(exclude []string) Map {
  5. excluded := make(Map)
  6. for k, v := range m {
  7. if !contains(exclude, k) {
  8. excluded[k] = v
  9. }
  10. }
  11. return excluded
  12. }
  13. // Copy creates a shallow copy of the Obj.
  14. func (m Map) Copy() Map {
  15. copied := Map{}
  16. for k, v := range m {
  17. copied[k] = v
  18. }
  19. return copied
  20. }
  21. // Merge blends the specified map with a copy of this map and returns the result.
  22. //
  23. // Keys that appear in both will be selected from the specified map.
  24. // This method requires that the wrapped object be a map[string]interface{}
  25. func (m Map) Merge(merge Map) Map {
  26. return m.Copy().MergeHere(merge)
  27. }
  28. // MergeHere blends the specified map with this map and returns the current map.
  29. //
  30. // Keys that appear in both will be selected from the specified map. The original map
  31. // will be modified. This method requires that
  32. // the wrapped object be a map[string]interface{}
  33. func (m Map) MergeHere(merge Map) Map {
  34. for k, v := range merge {
  35. m[k] = v
  36. }
  37. return m
  38. }
  39. // Transform builds a new Obj giving the transformer a chance
  40. // to change the keys and values as it goes. This method requires that
  41. // the wrapped object be a map[string]interface{}
  42. func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map {
  43. newMap := Map{}
  44. for k, v := range m {
  45. modifiedKey, modifiedVal := transformer(k, v)
  46. newMap[modifiedKey] = modifiedVal
  47. }
  48. return newMap
  49. }
  50. // TransformKeys builds a new map using the specified key mapping.
  51. //
  52. // Unspecified keys will be unaltered.
  53. // This method requires that the wrapped object be a map[string]interface{}
  54. func (m Map) TransformKeys(mapping map[string]string) Map {
  55. return m.Transform(func(key string, value interface{}) (string, interface{}) {
  56. if newKey, ok := mapping[key]; ok {
  57. return newKey, value
  58. }
  59. return key, value
  60. })
  61. }
  62. // Checks if a string slice contains a string
  63. func contains(s []string, e string) bool {
  64. for _, a := range s {
  65. if a == e {
  66. return true
  67. }
  68. }
  69. return false
  70. }