aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSamantha McVey <samantham@posteo.net>2017-04-24 14:44:48 -0700
committerSamantha McVey <samantham@posteo.net>2017-04-24 14:44:48 -0700
commit18e1a1ce36cbecd76f55ee46831a35849711d573 (patch)
treee9d9d88bee2f5218793aa2b867981a0a9d9a5725
parent8e7a339c33e24ba8c301c3dad05db4dfeba9508c (diff)
Get array merging functionality
-rw-r--r--lib/mergehash.pm627
-rw-r--r--t/01-thing.t13
2 files changed, 35 insertions, 5 deletions
diff --git a/lib/mergehash.pm6 b/lib/mergehash.pm6
index 206c881..6e84aa8 100644
--- a/lib/mergehash.pm6
+++ b/lib/mergehash.pm6
@@ -2,15 +2,32 @@ use MONKEY;
augment class Hash {
method merge (%b) {
hashmerge self, %b;
- self;
}
sub hashmerge (%merge-into, %merge-source) {
- for %merge-source.keys {
- if %merge-into{$_}:exists {
- hashmerge %merge-into{$_}, %merge-source{$_};
+ for %merge-source.keys -> $key {
+ if %merge-into{$key}:exists {
+ if %merge-source{$key} ~~ Hash {
+ hashmerge %merge-into{$key}, %merge-source{$key};
+ }
+ elsif %merge-source{$key} ~~ Positional {
+ my @a;
+ for %merge-into{$key}.list {
+ say $_;
+ @a.push: $_;
+ }
+ for %merge-source{$key}.list {
+ say $_;
+ @a.push: $_;
+ }
+ %merge-into{$key} = @a;
+ }
+ else {
+ %merge-into{$key} = %merge-source{$key};
+ }
}
else {
- %merge-into{$_} = %merge-source{$_};
+ note 'source';
+ %merge-into{$key} = %merge-source{$key};
}
}
%merge-into;
diff --git a/t/01-thing.t b/t/01-thing.t
index 6960a7a..9a906a7 100644
--- a/t/01-thing.t
+++ b/t/01-thing.t
@@ -16,3 +16,16 @@ my %a-orig = %a;
%a.merge(%b);
is-deeply %b, %b-orig;
is-deeply %a, {:a(2), :b(1), :y(${:a(1), :z(2)})};
+%a = %a-orig;
+%b = %b-orig;
+%a<Z> = "orig";
+%b<Z> = "new";
+is-deeply %a, {Z => 'new', a => 2, b => 1, y => {a => 1, z => 2}};
+say %a;
+my %z;
+%z<y><p> = (1,2,3,4);
+my %y;
+%y<y><p> = (5,4,6,7);
+%z.merge(%y);
+is %z, {y => {p => [1, 2, 3, 4, 5, 4, 6, 7]}}, "merges arrays";
+done-testing;