]> git.proxmox.com Git - pve-common.git/commitdiff
Add array_intersect and array_unique functions
authorStefan Reiter <s.reiter@proxmox.com>
Wed, 17 Jul 2019 13:03:44 +0000 (15:03 +0200)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Tue, 23 Jul 2019 06:46:49 +0000 (08:46 +0200)
Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
src/PVE/Tools.pm

index 4dd073f8cf6a07b02055fc0bb6a97b9145b2b1db..c31ebeb9e62421765b96835b2a4b3b04325f22dc 100644 (file)
@@ -1649,4 +1649,33 @@ sub dev_t_minor($) {
     return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff);
 }
 
     return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff);
 }
 
+# Given an array of array refs [ \[a b c], \[a b b], \[e b a] ]
+# Returns the intersection of elements as a single array [a b]
+sub array_intersect {
+    my ($arrays) = @_;
+
+    return [] if @$arrays == 0;
+    return $arrays->[0] if @$arrays == 1;
+
+    my $return_arr;
+    @$return_arr = array_unique(@{$arrays->[0]});
+    for my $i (1 .. $#$arrays) {
+       my %count = ();
+       foreach my $element (@$return_arr, array_unique(@{$arrays->[$i]})) {
+           $count{$element}++;
+       }
+       $return_arr = [];
+       foreach my $element (keys %count) {
+           push @$return_arr, $element if $count{$element} > 1;
+       }
+    }
+
+    return $return_arr;
+}
+
+sub array_unique {
+    my %seen = ();
+    return grep { ! $seen{ $_ }++ } @_;
+}
+
 1;
 1;