This should do it:
function getNext[num] {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var digits = num.toUpperCase[].split[""],
len = digits.length,
increase = true;
if [len != 3]
throw new Error["Invalid serial number length in getNext: "+num];
for [var i=len-1; increase && i>=0; i--] {
var val = alphabet.indexOf[digits[i]];
if [val == -1]
throw new Error["Invalid serial number digit in getNext: "+num];
val++;
if [val < alphabet.length] {
digits[i] = alphabet[val];
increase = false;
} else { // overflow
digits[i] = alphabet[0];
}
}
if [increase] // is still true
throw new Error["Serial number overflow in getNext"];
num = digits.join[""];
return num;
}
Since you are working with a nearly alphanumeric alphabet, a parseInt
/toString
with radix 33 might have done it as well. Only you need to "jump" over the 0
, I
and O
, that means replacing 0,A,B…
by A,B,C…
, replacing H,I,J…
by J,K,L…
and replacing M,N,O…
by P,Q,R…
[and everything back on deserialisation] - which might be OK if JS has a numeric char
datatype, but I think it's easier to do it manually as
above.
If you're curious:
String.prototype.padLeft = function[n, x] {
return [new Array[n].join[x || "0"]+this].slice[-n];
};
function getNext[num] {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var back = {}, forth = {};
for [var i=0; i