File Coverage

blib/lib/Role/TinyCommons/Collection/PickItems/RandomPos.pm
Criterion Covered Total %
statement 6 21 28.5
branch 0 10 0.0
condition 0 2 0.0
subroutine 2 3 66.6
pod 0 1 0.0
total 8 37 21.6


line stmt bran cond sub pod time code
1             package Role::TinyCommons::Collection::PickItems::RandomPos;
2              
3 1     1   407851 use Role::Tiny;
  1         7051  
  1         11  
4 1     1   819 use Role::Tiny::With;
  1         364  
  1         311  
5              
6             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
7             our $DATE = '2024-01-16'; # DATE
8             our $DIST = 'Role-TinyCommons-Collection'; # DIST
9             our $VERSION = '0.010'; # VERSION
10              
11             requires 'get_item_count';
12             requires 'get_item_at_pos';
13              
14             with 'Role::TinyCommons::Collection::PickItems';
15              
16             sub pick_items {
17 0     0 0   my ($self, %args) = @_;
18              
19 0   0       my $n = $args{n} || 1;
20 0 0         my $allow_resampling = defined $args{allow_resampling} ? $args{allow_resampling} : 0;
21 0           my $item_count = $self->get_item_count;
22              
23             # got an infinite collection?
24 0 0         if ($item_count == -1) {
25 0           warn "Got infinite item count (-1), setting item_count = 2**31 -1";
26 0           $item_count = 2**31 - 1;
27             }
28              
29 0 0         $n = $item_count if $n > $item_count;
30              
31 0           my @items;
32             my %used_pos;
33 0           while (@items < $n) {
34 0           my $pos = int(rand() * $item_count);
35 0 0         unless ($allow_resampling) {
36 0 0         next if $used_pos{$pos}++;
37             }
38 0           push @items, $self->get_item_at_pos($pos);
39             }
40 0           @items;
41             }
42              
43             1;
44             # ABSTRACT: Provide pick_items() that picks items by random positions
45              
46             __END__