Next 0-Z Sequence Code with Javascript

Asked

Viewed 153 times

2

I need to create a Javascript function that takes a string of letters and numbers and it returns the next count value. The count goes from 0 to Z. Example of the sequence:

0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - A - B - C - D [...] Y - Z - 01 - 02 - 03 [...] 0Y - 0Z - 10 - 11 - 12 [...]

Example of the function:

nextCode ("AF10") // Returns "AF11"

nextCode ("A4ZZ") // Returns "A500"


What I’ve tried so far:

/*Gerar Novo Código*/
function nextCode(lastCode){
    //Verifica o Tamanho
    var codeSize = lastCode.length;
    //Verifica o index do ultimo caracter
    var indexLastValidChar = codeSize-1;
    //Se o ultimo caracter for igual a Z pega o caractere anterior (loop)
    var loopAtive;
    do {
        indexLastValidChar = loopAtive == true ?  indexLastValidChar-1 :indexLastValidChar;
        var lastValidChar = lastCode.substr(indexLastValidChar, 1);
        loopAtive = true;
    } while(lastValidChar == "Z");
    //Pega a primeira metade do novo código
    var firstHalfCode = lastCode.slice(0, indexLastValidChar);
    //Verifica se o ultimo caracter diferente de Z é numero ou letra
    var isChar = isNaN(parseInt(lastValidChar));
    //Se for char, gera o próximo caracter
    var newChar;
    if (isChar){
        newChar = String.fromCharCode(lastValidChar.charCodeAt(0)+1);
    } //Se não for, verifica se o número é 9
    else if (lastValidChar == "9") {
        newChar = "A";
    }  //Se não for, adicona um ao número
    else {
        newChar = parseInt(lastValidChar) + 1;
    }
    //Junta primeira metade
    firstHalfCode = firstHalfCode + newChar;
    //Adicona zeros ao final, caso codeSize seja diferente de indexLastValidChar+1 - ou seja, existem Zs
    for (var i = 0; i < codeSize - indexLastValidChar+1; i++) {
        var newCode = firstHalfCode + 0;
    }
    //Mostra o novo código
    console.log(newCode);
}
nextCode ("AF10");
nextCode ("A4ZZ");

The results don’t work out and I’m a little lost...

  • 1

    Add to your question what you have so far.

  • 1

    I added to the question !

  • It seems to me that you are wanting to work on 36 basis. After Z would not see the value 10? It needs after Z to be even 01?

2 answers

3

From the understanding of the question, it seems that you are willing to work with a 36 basis, but the sequence example described in the question does not fall right into the 36 basis. The examples of sequences of "AF10" -> "AF11" and "A4ZZ" -> "A500" are correct, but following base 36 the number after "Z" would be "10". If this is the case, just use the functions parseInt and String.prototype.toString, which allow the base to be passed per parameter.

var nextCode = function(number) {
  var inBase10 = parseInt(number, 36);
  return (inBase10 + 1).toString(36).toUpperCase();
};

nextCode('AF10'); // => "AF11"
nextCode('A4ZZ'); // => "A500"
  • Good answer! +1

  • Thanks Gabriel, I think a sequence in base 36 is really more coherent. Good answer. Little code and very effective.

2


If you know the String that you have of characters you can use a loop to make these changes/increments. Using flags to coltrolar if you should increment.

Suggestion:

var Next = (function(seq) {
  var lastChar = seq.slice(-1);

  return function(str) {
    if (!str) return '0';
    var chars = str.split('');
    var raize = true,
      addChar = false;
    for (var i = chars.length - 1; i + 1; i--) {
      var charIndex = seq.indexOf(chars[i]);
      if(!raize) continue;
      if (chars[i] !== lastChar) {
        if (!raize) break;
        chars[i] = seq[charIndex + 1];
        raize = false;
      } else {
        chars[i] = seq[0];
        raize = true;
        if (raize && i == 0) chars.unshift(seq[0]);
      }
    }
    return chars.join('');
  }

})('0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ');

['', '00', '0Z', 'ZZ', 'AF10', 'A4ZZ', 'A4Z0'].forEach(test => console.log(test, Next(test)));

  • If you follow the model proposed in the question, you have a problem. Next('A4Z0') is returning "A501", something that should only be for "A500".

  • The Y letter is also missing from the Next startup.

  • @Gabrielkatakura well seen, corrected!

  • 1

    Thanks @Sergio ! I was impressed, as it also serves for other sequences, just change the parameters in the invocation of the IIFE. I tested with other sequences and it works cool. Congratulations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.