Skip to content

Comments

Added :preserve_key_order option to maintain original hash key order#99

Merged
liufengyun merged 2 commits intoliufengyun:masterfrom
robkiessling:preserve-key-order
May 20, 2025
Merged

Added :preserve_key_order option to maintain original hash key order#99
liufengyun merged 2 commits intoliufengyun:masterfrom
robkiessling:preserve-key-order

Conversation

@robkiessling
Copy link
Contributor

This is in response to issue #98, which requests an option to preserve the original key order of compared hashes.

The existing implementation always outputs changes in a fixed order:

  1. Deletions (-)
  2. Updates (~)
  3. Additions (+)

And within each group, keys are sorted alphabetically.

Unfortunately, this means that simply disabling sort_by here isn’t enough:

added_keys = (obj2_keys - obj1_keys).sort_by(&:to_s)
common_keys = (obj1_keys & obj2_keys).sort_by(&:to_s)
deleted_keys = (obj1_keys - obj2_keys).sort_by(&:to_s)

because grouping by operation type still forces a reordering that doesn’t reflect the original hash structure.

My goal for this option is to have all deletions and updates listed in the order they appear in the first hash. Then, similar to how Ruby’s Hash#merge appends new keys, any keys found only in the second hash are appended in their original order.

To support this behavior, the logic for handling deletions, updates, and additions was unified into a handle_key lambda. This allows each key to be evaluated in sequence, rather than processing all deletions, then all updates, then all additions in separate passes. I chose a lambda (instead of a separate method) to avoid having to pass in the many options and lookups needed within handle_key.

Copy link
Owner

@liufengyun liufengyun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @robkiessling , LGTM 🎉

@liufengyun liufengyun merged commit d34f549 into liufengyun:master May 20, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants