diff options
author | Patrick Spek <p.spek@tyil.nl> | 2017-04-25 09:52:04 +0200 |
---|---|---|
committer | Patrick Spek <p.spek@tyil.nl> | 2017-04-25 09:54:38 +0200 |
commit | 1040a65e6416d4a9c7f758093d4b17f684e1ddbe (patch) | |
tree | ebf9d2e34a5ce5e8bfa2eba99ea65692d1de4958 /lib/Hash | |
parent | cb5db41329c1aab1cb56d7a3e381c53d668af844 (diff) |
Rename to Hash::Merge
Diffstat (limited to 'lib/Hash')
-rw-r--r-- | lib/Hash/Merge.pm6 | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/Hash/Merge.pm6 b/lib/Hash/Merge.pm6 new file mode 100644 index 0000000..b24f25d --- /dev/null +++ b/lib/Hash/Merge.pm6 @@ -0,0 +1,51 @@ +#! /usr/bin/env false + +use v6.c; +use MONKEY; + +augment class Hash +{ + #| Merges a second hash into the hash the method is called on. Hash given as + #| the argument is not modified. + #| Traverses the full tree, replacing items in the original hash with the + #| hash given in the argument. Does not replace positional elements by default, + #| and instead appends the items from the supplied hash's array to the original + #| hash's array. The object type of positionals is not retained and instead + #| becomes an Array type. + #| Use :no-append-array to replace arrays and positionals instead, which will + #| also retain the original type and not convert to an Array + #| + method merge (%b; Bool:D :$no-append-array = False) + { + hashmerge self, %b, :$no-append-array; + } + + sub hashmerge (%merge-into, %merge-source, Bool:D :$no-append-array) + { + for %merge-source.keys -> $key { + if %merge-into{$key}:exists { + if %merge-source{$key} ~~ Hash { + hashmerge %merge-into{$key}, %merge-source{$key}, :$no-append-array; + } elsif %merge-source{$key} ~~ Positional { + if $no-append-array { + %merge-into{$key} = %merge-source{$key}; + } else { + my @a; + + @a.push: $_ for %merge-into{$key}.list; + @a.push: $_ for %merge-source{$key}.list; + + %merge-into{$key} = @a; + } + } else { + # Non-positionals, so strings or Bools or whatever + %merge-into{$key} = %merge-source{$key}; + } + } else { + %merge-into{$key} = %merge-source{$key}; + } + } + + %merge-into; + } +} |