Javascript: Letter incrementation à la PHP/Perl – Part 1

Have you ever needed to do an auto-increment on a letter in Javascript? It's built into PHP and Perl ($a = 'A'; $a++; # $a is now 'B'), but I recently found that trying to do it in Javascript may be harder than one thinks. After lots of time lost searching the web for a solution that suited my needs, I gave up and decided to invent the wheel (since no existing wheel was to be found anywhere).

Although I didn't implement the auto- portion of the auto-increment, I did successfully manage to do the incrementing.

In this article I will show you how to implement an incrementing string counter, and on

Javascript: Letter incrementation à la PHP/Perl - Part 2

I will use this logic to create a increment/decrement on a given string. To easily change this from increment to decrement, just invert the charString values to reflect Z to A.

String Counter:
The code:

var charArray = new Array('-1');
var	charString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function stringCounter(charString,charArray) {

	var str='';
	var maxVal = charString.length-1;

	// increment greatest index
	++charArray[charArray.length-1];

	// if greatest index == maxVal+1
	if (charArray[charArray.length-1] == maxVal+1) {
		// iterate from max to first and increment
		for (i=charArray.length;i>0;i--){
			if (charArray[i] == maxVal+1) {
				charArray[i-1]++; // increment previous character
				charArray[i]=0; // reset current character
			}
		}
	}

	// if first index surpasses the available sting, then
	// reset whole counter and add one char
	if (charArray[0] == maxVal+1) {
		for (i=0;i<charArray.length;i++) {
			charArray[i] = 0; // zeros counter on all indexes
		}
		charArray[charArray.length]=0; // appends a new index
	}

	// Prepare output by translating numbers and
	// contatenating results
	for (i=0;i<charArray.length;i++) {
		str += charString.charAt(charArray[i]);
	}

	return str;
}

The Explanation:
Lines 1 and 2: Initialize your global variables - the array that will keep the characters (array charArray having one element with value -1) and the available character range (charString having the alphabet). You can modify the value of charString to whatever you want - the logic will append a new character to the result string starting from the first one in charString.

Lines 6 and 7: Initialize the str variable which will have the end results. Get maxVal having the length of charString - 1 (since indexes start at 0).

Line 10: Auto-increment the value of the last element. Last element index is found by subtracting 1 from the length of the array.
E.g: If the array contains only one index, the change would be from A to B, from B to C... If it has 2 indexes, it would be from AA to AB, AB to AC, and so on.

Lines 13 to 21: This block is used to do the resetting of all the previous characters up to the second one. It will happen only if the value of the last index has reached its maximum.
E.g: AAZ -> ABA; AZZ -> BAA

Lines 23 to 30: Here we handle cases where all indexes have reached the last character of our charString. It will zero the counter and add a new element to the array.
E.g: Z -> AA; ZZ -> AAA; ZZZ-> AAAA

Lines 34 to 38: Finally we reach the place where we iterate through our charArray and concatenate the values into variable str to be returned.

To see the code in action, use the following HTML/Javascript:

<html>
<head>
<script language="javascript" type="text/javascript">

var charArray = new Array('-1');
var	charString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function stringCounter(charString,charArray) {

	var str='';
	var maxVal = charString.length;

	// increment greatest index
	++charArray[charArray.length-1];

	// if greatest index == maxVal+1
	if (charArray[charArray.length-1] == maxVal+1) {
		// iterate from max to first and increment
		for (i=charArray.length;i>0;i--){
			if (charArray[i] == maxVal+1) {
				charArray[i-1]++; // increment previous character
				charArray[i]=0; // reset current character
			}
		}
	}

	// if first index surpasses the available sting, then
	// reset whole counter and add one char
	if (charArray[0] == maxVal+1) {
		for (i=0;i<charArray.length;i++) {
			charArray[i] = 0; // zeros counter on all indexes
		}
		charArray[charArray.length]=0; // appends a new index
	}

	// Prepare output by translating numbers and
	// contatenating results
	for (i=0;i<charArray.length;i++) {
		str += charString.charAt(charArray[i]);
	}

	return str;
}
</script>
</head>
<body>
<a href="javascript:;" onclick="alert(stringCounter());">showCounter</a>
</body>
</html>

I hope this is as useful to you as it has been to me. Being a Perl/PHP programmer, I never thought I'd have so much trouble with a little thing such as this.

9 comments to Javascript: Letter incrementation à la PHP/Perl – Part 1

  • carl

    Looks cool and all, but I am having difficulties adapting it to run as a per script. I want to run it from teh command line in linux as a perl script and dump the output to the screen.

    Any thoughts?

    • Vinny

      Perl (as well as PHP) has it built in. All you have to do is assign a string to a variable and then auto-increment ($var++) that string.

      $ perl -e ‘$var = “a”;
      while ($var ne “ccc”) {
      print “$var\n”;
      $var++;
      }’

      Looks like auto-decrement doesn’t work though.

  • carl

    This would work except that I need to increment more than just alph or numaric. I need to use an array of chars as I want to leave out some (lower case l for example ) and include others like 2,3 4 5,and so on.. That is why I was wanting to define an array and then only use the chars in the array as the count..
    take the array (a b c 1 2 3 4) for anexample. I would want it to count like so..
    a
    b
    c
    1
    2
    3
    4
    aa
    ab
    ac
    a1
    a2
    a3
    a4

    and so on.

    Carl

  • Vinny

    Gotcha – what does your code look like and what’s the error you’re getting?

  • carl

    The error is
    Can’t modify non-lvalue subroutine call at alt line 14.

    Line 14 is
    ++charArray(charArray.length(-1));

    My code is
    #!/usr/bin/perl

    @charArray = (“-1″);
    $charString = “ABC1234xyz”;

    stringCounter();

    sub stringCounter(charString,charArray) {
    $str=”;
    $maxVal = charString.length(-1);

    # // increment greatest index
    ++charArray(charArray.length(-1));

    # // if greatest index == maxVal+1
    if (charArray(charArray.length(-1)) == maxVal+1) {
    # iterate from max to first and increment
    for ($i = charArray.length; $i > 0; $i–){
    if (charArray($i) == maxVal+1) {
    charArray($i-1)++; # // increment previous character
    charArray($i)=0; # // reset current character
    }
    }
    }

    # // if first index surpasses the available sting, then
    # // reset whole counter and add one char
    if (charArray(0) == maxVal+1) {
    for ($i=0;$i<charArray.length;$i++) {
    charArray($i) = 0; # // zeros counter on all indexes
    }
    charArray(charArray.length)=0; # // appends a new index
    }

    # // Prepare output by translating numbers and
    # // contatenating results
    for ($i=0;$icharAt(charArray($i));
    $str += charString.charAt(charArray($i));
    }

    return $str;
    }
    # FINISH THE TABLE

  • Vinny

    Looks like you missed language translation at several points. Below is a the perl equivalent to the javascript code using the string you want. There’s probably a faster/cleaner/better way to do it in Perl (as usual), but I just focused on the literal translation.

    #!/usr/bin/perl

    use strict;

    my @charArray = (-1);
    my $charString = ‘ABC1234xyz’;

    print stringCounter(), “\n”;

    sub stringCounter(@) {

    # the below comments make it work on
    # the global values and keep the counter
    # incrementing.

    #my $charString = shift;
    #my @charArray = @{ shift() };

    my $str = undef;
    my $maxVal = length($charString)-1;

    # increment greatest index

    ++$charArray[@charArray-1];

    # if greatest index == maxVal+1
    if ($charArray[-1] == $maxVal+1) {

    for (my $i=@charArray;$i>0;$i–){

    if ($charArray[$i] == $maxVal+1) {

    $charArray[$i-1]++; # increment previous character
    $charArray[$i]=0; # reset current character

    }
    }
    }

    # if first index surpasses the available sting, then
    # reset whole counter and add one char
    if ($charArray[0] == $maxVal+1) {
    for (my $i=0;$i<@charArray;$i++) {

    $charArray[$i] = 0; # zeros counter on all indexes

    }

    $charArray[@charArray]=0; # appends a new index
    }

    #Prepare output by translating numbers and
    # concatenating results
    for (my $i=0;$i<@charArray;$i++) {
    $str .= substr($charString,$charArray[$i],1);
    }

    return $str;

    }

    Hope it helps.

  • carl

    Thank you for your willingness to help.

    I tried teh new code and still got compile errors. Some of them I was able to fix , but I am now down to the las one that I aam unsure of. The error is
    syntax error at more line 12, near “sub stringCounter(@) ”
    syntax error at more line 63, near “}”

    I am not sure what the “@” is trying to pass. I have tried everything I can think of, but wanted to see if you know what was wrong before I go nuts for something simple.. Here is the new code

    #!/usr/bin/perl

    use strict;

    my @charArray = (-1);
    my $charString = ‘ABC1234xyz’;

    my $result = stringCounter();

    print “$result\n”

    sub stringCounter(@) {

    # the below comments make it work on
    # the global values and keep the counter
    # incrementing.

    #my $charString = shift;
    #my @charArray = @{ shift() };

    my $str = undef;
    my $maxVal = length($charString)-1;

    # increment greatest index

    ++$charArray[@charArray-1];

    # if greatest index == maxVal+1
    if ($charArray[-1] == $maxVal+1) {

    ## for (my $i=@charArray;$i>0;$i–){
    ## Edited this line it is erroring at the “–){” Section
    for (my $i=@charArray;$i>0;$i–){

    if ($charArray[$i] == $maxVal+1) {

    $charArray[$i-1]++; # increment previous character
    $charArray[$i]=0; # reset current character

    }
    }
    }

    # if first index surpasses the available sting, then
    # reset whole counter and add one char
    if ($charArray[0] == $maxVal+1) {
    for (my $i=0;$i<@charArray;$i++) {

    $charArray[$i] = 0; # zeros counter on all indexes

    }

    $charArray[@charArray]=0; # appends a new index
    }

    #Prepare output by translating numbers and
    # concatenating results
    for (my $i=0;$i<@charArray;$i++) {
    $str .= substr($charString,$charArray[$i],1);
    }

    return $str;
    }

  • carl

    Corrected

    New code:
    #!/usr/bin/perl

    use strict;

    my @charArray = (-1);
    my $charString = ‘ABC1234xyz’;

    my $result = stringCounter();

    print “$result\n”;

    sub stringCounter(@) {

    # the below comments make it work on
    # the global values and keep the counter
    # incrementing.

    # my $charString = shift;
    # my @charArray = @{ shift() };

    my $str = undef;
    my $maxVal = length($charString)-1;

    # increment greatest index

    ++$charArray[@charArray-1];

    # if greatest index == maxVal+1
    if ($charArray[-1] == $maxVal+1) {

    ## for (my $i=@charArray;$i>0;$i–){
    ## Edited this line it is erroring at the “–){” Section
    for (my $i=@charArray;$i>0;$i–){

    if ($charArray[$i] == $maxVal+1) {
    $charArray[$i-1]++; # increment previous character
    $charArray[$i]=0; # reset current character
    }
    }
    }

    # if first index surpasses the available sting, then
    # reset whole counter and add one char
    if ($charArray[0] == $maxVal+1) {
    for (my $i=0;$i<@charArray;$i++) {
    $charArray[$i] = 0; # zeros counter on all indexes
    }
    $charArray[@charArray]=0; # appends a new index
    }

    #Prepare output by translating numbers and
    # concatenating results
    for (my $i=0;$i<@charArray;$i++) {
    $str .= substr($charString,$charArray[$i],1);
    }

    return $str;
    }

  • Vinny

    Yep, it was that blasted semi-colon…

    sub somefunction(@) { }

    the @ isn’t passing, but receiving. it’s the protocol that says that I’ll be passing 1 or more values into the function. I’ll post more about them once I find a good source (don’t really use them that much).

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>