lib/Wildling/Token.pm untested

filter: Statementstmt 0.0% 0 / 44 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 91 CC 8 SCAR 25.5
CC
8
Cov
0%
get
20.0
_default_integer
20.0
new
6.0
CRAP 12.9
1 package Wildling::Token;
2  
3 use strict;
4 use warnings;
5  
6 sub new {
7 my ( $class, $options ) = @_;
8 $options ||= {};
9  
10 my $src = exists $options->{src} ? $options->{src} : '';
11 my $start_length = _default_integer( $options->{startLength}, 1 );
12 my $end_length = _default_integer( $options->{endLength}, 1 );
13 my $variants = $options->{variants} || [];
14  
15 my $count = 0;
16 my $n = scalar @$variants;
17 for my $length ( $start_length .. $end_length ) {
18 $count += $n**$length;
19 }
20  
21 return bless {
22 src => $src,
23 start_length => $start_length,
24 end_length => $end_length,
25 variants => $variants,
26 count => $count,
27 }, $class;
28 }
29  
30 sub count {
31 my ($self) = @_;
32 return $self->{count};
33 }
34  
35 sub src {
36 my ($self) = @_;
37 return $self->{src};
38 }
39  
40 sub get {
41 my ( $self, $index ) = @_;
42 return '' if $index > $self->{count} - 1 || $index < 0;
43 return '' if $index == 0 && $self->{start_length} == 0;
44  
45 my $index_with_offset = $index;
46 my $string_length = $self->{start_length};
47 my $n = scalar @{ $self->{variants} };
48  
49 for my $length ( $self->{start_length} .. $self->{end_length} ) {
50 $string_length = $length;
51 my $offset_count = $n**$length;
52 last if $index_with_offset < $offset_count;
53 $index_with_offset -= $offset_count;
54 }
55  
56 my @string_array;
57 for ( 1 .. $string_length ) {
58 my $variant_index = $index_with_offset % $n;
59 $index_with_offset = int( $index_with_offset / $n );
60 push @string_array, $self->{variants}[$variant_index];
61 }
62 return join '', @string_array;
63 }
64  
65 sub _default_integer {
66 my ( $option, $fallback ) = @_;
67 return $fallback unless defined $option && !ref($option);
68 return $fallback unless $option =~ /\A(?:0|[1-9][0-9]*)\z/;
69 my $n = 0 + $option;
70 return $n >= 0 ? $n : $fallback;
71 }
72  
73 1;