liufengyun / hashdiff

Hashdiff is a ruby library to to compute the smallest difference between two hashes
MIT License
559 stars 63 forks source link

[Feature request] :ignore_keys option #86

Closed MatzFan closed 10 months ago

MatzFan commented 11 months ago

I have a use-case where I often need to compare 2 hashes where I don't care about the values of particular keys. For example ones which contain timestamps, or the following example which contain a 'duration' key (representing milliseconds):

h1 = 
{
  "fonts": {
    "value": [],
    "duration": 93
  },
  "domBlockers": {
    "duration": 0
  },
  "fontPreferences": {
    "value": {
      "default": 146,
      "apple": 146,
      "serif": 146,
      "sans": 144,
      "mono": 119,
      "min": 10,
      "system": 144
    },
    "duration": 117
  },
# ...
}

h2 = 
{
  "fonts": {
    "value": [],
    "duration": 78
  },
  "domBlockers": {
    "duration": 0
  },
  "fontPreferences": {
    "value": {
      "default": 146,
      "apple": 146,
      "serif": 146,
      "sans": 144,
      "mono": 119,
      "min": 10,
      "system": 146
    },
    "duration": 134
  },
# ...
}

I can ignore differences in the 'duration' values with a block:

diff = Hashdiff.diff(h1, h2) { |path, _e, _a| true if path.split('.').last == 'duration' }
#=> [['~', 'fontPreferences.value.system', 144, 146]]

But I'd love to be able to write something like this, where :ignore_keys can take a single value or array of keys to ignore:

diff  = Hashdiff.diff(h1, h2, ignore_keys: 'duration')

The logic would be the same as above, i.e. ignored keys would have to be at the end of each path. My guess is this may be a common enough use-case that a shorthand option like this would be valuable to users.

I might have a stab at a PR if you like the idea. Awesome library btw.

luis-ca commented 10 months ago

+1

liufengyun commented 10 months ago

Thanks for the detailed explanation of the use case @MatzFan . It sounds like a useful feature.

A PR is welcome from anyone who has bandwidth to do it.

liufengyun commented 10 months ago

V1.1.0 now contains this feature, kudos to @MatzFan 🎉