|
|||||
Javascript: Letter incrementation à la PHP/Perl – Part 1Have 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
String Counter:
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 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. 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. 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. 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 |
|||||
|
Copyright © 2010 use strict ;#) - All Rights Reserved |
|||||
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?
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.
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
Gotcha – what does your code look like and what’s the error you’re getting?
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
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.
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;
}
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;
}
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).