Add _num_to_alpha() to test.pl
authorBrad Gilbert <b2gills@gmail.com>
Sun, 16 Sep 2012 19:06:59 +0000 (14:06 -0500)
committerFather Chrysostomos <sprout@cpan.org>
Tue, 25 Sep 2012 21:35:12 +0000 (14:35 -0700)
Also added testing for _num_to_alpha()

t/test.pl
t/test_pl/_num_to_alpha.t [new file with mode: 0644]

index 65e2348..da480d3 100644 (file)
--- a/t/test.pl
+++ b/t/test.pl
@@ -762,8 +762,34 @@ sub unlink_all {
     $count;
 }
 
+# _num_to_alpha - Returns a string of letters representing a positive integer.
+# Arguments :
+#   number to convert
+
+# returns undef if the number is negative
+
+# _num_to_alpha( 0) eq 'A';
+# _num_to_alpha( 1) eq 'B';
+# _num_to_alpha(25) eq 'Z';
+# _num_to_alpha(26) eq 'AA';
+# _num_to_alpha(27) eq 'AB';
+
 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) = @_;
+    return unless $num >= 0;
+    my $alpha = '';
+    while( 1 ){
+        $alpha = $letters[ $num % 26 ] . $alpha;
+        $num = int( $num / 26 );
+        last if $num == 0;
+        $num = $num - 1;
+    }
+    return $alpha;
+}
+
 my %tmpfiles;
 END { unlink_all keys %tmpfiles }
 
diff --git a/t/test_pl/_num_to_alpha.t b/t/test_pl/_num_to_alpha.t
new file mode 100644 (file)
index 0000000..8897f05
--- /dev/null
@@ -0,0 +1,34 @@
+#!./perl
+
+BEGIN {
+    chdir 't' if -d 't';
+    @INC = '../lib';
+    require './test.pl';
+}
+
+is( _num_to_alpha(-1), undef);
+is( _num_to_alpha( 0), 'A');
+is( _num_to_alpha( 1), 'B');
+
+is( _num_to_alpha(26 - 1), 'Z');
+is( _num_to_alpha(26    ), 'AA');
+is( _num_to_alpha(26 + 1), 'AB');
+
+is( _num_to_alpha(26 + 26 - 2), 'AY');
+is( _num_to_alpha(26 + 26 - 1), 'AZ');
+is( _num_to_alpha(26 + 26    ), 'BA');
+is( _num_to_alpha(26 + 26 + 1), 'BB');
+
+is( _num_to_alpha(26 ** 2 - 1), 'YZ');
+is( _num_to_alpha(26 ** 2    ), 'ZA');
+is( _num_to_alpha(26 ** 2 + 1), 'ZB');
+
+is( _num_to_alpha(26 ** 2 + 26 - 1), 'ZZ');
+is( _num_to_alpha(26 ** 2 + 26    ), 'AAA');
+is( _num_to_alpha(26 ** 2 + 26 + 1), 'AAB');
+
+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');
+
+done_testing();