Added optional char limit to _num_to_alpha() in test.pl
authorBrad Gilbert <b2gills@gmail.com>
Sun, 16 Sep 2012 19:25:19 +0000 (14:25 -0500)
committerFather Chrysostomos <sprout@cpan.org>
Tue, 25 Sep 2012 21:35:12 +0000 (14:35 -0700)
t/test.pl
t/test_pl/_num_to_alpha.t

index da480d3..5c7d737 100644 (file)
--- a/t/test.pl
+++ b/t/test.pl
@@ -765,8 +765,10 @@ sub unlink_all {
 # _num_to_alpha - Returns a string of letters representing a positive integer.
 # Arguments :
 #   number to convert
+#   maximum number of letters
 
 # returns undef if the number is negative
+# returns undef if the number of letters is greater than the maximum wanted
 
 # _num_to_alpha( 0) eq 'A';
 # _num_to_alpha( 1) eq 'B';
@@ -778,14 +780,22 @@ my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
 
 # Avoid ++ -- ranges split negative numbers
 sub _num_to_alpha{
-    my($num) = @_;
+    my($num,$max_char) = @_;
     return unless $num >= 0;
     my $alpha = '';
+    my $char_count = 0;
+    $max_char = 0 if $max_char < 0;
+
     while( 1 ){
         $alpha = $letters[ $num % 26 ] . $alpha;
         $num = int( $num / 26 );
         last if $num == 0;
         $num = $num - 1;
+
+        # char limit
+        next unless $max_char;
+        $char_count = $char_count + 1;
+        return if $char_count == $max_char;
     }
     return $alpha;
 }
index 8897f05..93ddcf2 100644 (file)
@@ -2,7 +2,6 @@
 
 BEGIN {
     chdir 't' if -d 't';
-    @INC = '../lib';
     require './test.pl';
 }
 
@@ -31,4 +30,13 @@ is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 - 1 ), 'ZZZ');
 is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26     ), 'AAAA');
 is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 + 1 ), 'AAAB');
 
+is( _num_to_alpha(26 - 1 , 1), 'Z');
+is( _num_to_alpha(26     , 1), undef); # AA
+
+is( _num_to_alpha(26 ** 2 + 26 - 1 , 2 ), 'ZZ');
+is( _num_to_alpha(26 ** 2 + 26     , 2 ), undef); # AAA
+
+is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 - 1 , 3 ), 'ZZZ');
+is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26     , 3 ), undef); # AAAA
+
 done_testing();