Many/Scheduler/UniquenessScheduler/WeightedRandom.pm untested

filter: Statementstmt 0.0% 0 / 36 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 5 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 50 CC 2 SCAR 12.0
CC
2
Cov
0%
new
6.0
_get_next
2.0
BEGIN
2.0
CRAP 3.3
1 package Geo::Coder::Many::Scheduler::UniquenessScheduler::WeightedRandom;
2  
3 use strict;
4 use warnings;
5  
6 use base 'Geo::Coder::Many::Scheduler::UniquenessScheduler';
7  
8 our $VERSION = '0.01';
9  
10 =head1 NAME
11  
12 Geo::Coder::Many::Scheduler::WeightedRandom - Weighted random scheduler
13  
14 =head1 DESCRIPTION
15  
16 A scheduler which randomly picks an item from the list, with the probability of
17 each proportional to its weight.
18  
19 =head1 METHODS
20  
21 =head2 new
22  
23 Construct and return a new scheduler for the array of pairs of geocoder names
24 and weights whose reference is passed in.
25  
26 =cut
27  
28 sub new {
29 my $class = shift;
30 my $ra_geocoders = shift;
31  
32 # Convert weights (= desired frequencies) into a cumulative distribution
33 # function
34 my $total_weight = 0;
35 for my $rh_geo (@$ra_geocoders) {
36 my $weight = $rh_geo->{weight};
37 if ($weight <= 0) {
38 warn "Warning - weight for "
39 .$rh_geo->{geocoder}
40 ." should be greater than zero";
41 }
42 $rh_geo->{weight} = $weight + $total_weight;
43 $total_weight += $weight;
44 }
45 # (Normalization)
46 for (@$ra_geocoders) {
47 $_->{weight} /= $total_weight;
48 }
49
50 my $self = $class->SUPER::new({items => $ra_geocoders});
51  
52 bless $self, $class;
53  
54 my @sorted = sort { $b->{weight} <=> $a->{weight} } @$ra_geocoders;
55 $self->{ ra_geocoders } = \@sorted;
56  
57 return $self;
58 };
59  
60 =head1 INTERNAL METHODS
61  
62 =head2 _get_next
63  
64 Overrides the method of the same name from the parent class, and is called by
65 get_next_unique instead.
66  
67 =cut
68  
69 ## no critic (ProhibitUnusedPrivateSubroutines)
70 # ( _get_next is actually 'protected' )
71  
72 sub _get_next {
73 my $self = shift;
74 my $r = rand;
75  
76 my $ra_geocoders = $self->{ra_geocoders};
77  
78 my $i = @$ra_geocoders - 1;
79 while ($i > 0 and $r > $self->{ra_geocoders}->[$i]->{weight}) { --$i; }
80 return $self->{ra_geocoders}->[$i]->{name};
81  
82 };
83  
84 1;
85  
86 __END__