Pergunta

I need a function in JavaScript (for use in Node) that increments numbers in a string as follows:

"0", "1", "2", "3", ..., "8", "9", "00", "01", "02"

and so on. How would I go about doing this? I can think of a long way with lots of conditionals, but that probably won't run optimally.


What I have so far:

var count = "0";

function increment() {
    var number = parseInt(count), digits = count.length;
    var upDigit = true;
    for (var i = 0; i < digits; i++) {
        if (i !== 9)
            upDigit = false;
    }
    if (upDigit) {
        var zeros = "";
        for (var i = 0; i <= digits; i++) {
            zeros += "0";
        }
        count = zeros;
    } else {
        count = number++;
    }
}
Foi útil?

Solução 2

function zeroPad(str, ln){
  if(str.length > ln){ raise('Trying to zero pad a too-long string') };
  var out = str;
  while(out.length !== ln){
    out = '0'+out;
  };
  return out;
}

function iterate(previous, final){
  console.log(previous);
  if(previous === final){ return };
  var next = "";
  var ln = previous.length; // how many characters so far
  // use a regex to test if every character is 9
  var nines = 
    previous.match(/^9+$/) ? true : false;
  if(nines){
    for(var i=0; i<ln+1; i++){
      next += "0";
    }
    return iterate(next, final);
  } else {
    var value = +previous; // coerce to number
    value += 1;
    next = zeroPad(String(value), ln)
    return iterate(next, final);
  }
};

iterate("0", "000");

Outras dicas

Based on my previous answer :

function range(i, to) {
    var v,
        r = [],
        s = to,
        e = i.length,
        t = Math.pow(10, e),
        l = (t + '').length;
    i = parseInt(i);
    to = Math.pow(10, to.length);
    for (; i <= to; i++) {
        if (i === t) {
            i = 0;
            t = Math.pow(10, ++e);
            l = (t + '').length;
        }
        v = new Array(l - (i + '').length).join('0') + i;
        r.push(v);
        if (v === s) { break; }
    }
    return r;
}

Usage example :

console.log(range('05', '15').join()); // "05,06,07,08,09,10,11,12,13,14,15"

Is this the result you were expecting?

var e = 0,
    t = 0,
    l = 0,
    i = 0;
for (; i <= 100; i++) {
    if (i >= t) {
        i = 0;
        t = Math.pow(10, ++e);
        l = (t + '').length;
    }
    console.log(new Array(l - (i + '').length).join('0') + i);
}

Padding method :

new Array(2).join('0') == ['', ''].join('0') == '0'; // true
function pad(num) {
  return num > 0 ? pad(num-1) + "0" : ""; 
}

function add(str) {
    var len, num, numlen;
    len = str.length;
    num = +str;
    numlen = String(num).length;
    if (/^9+$/.test(num)) { return pad(len + 1); }
    else { return pad(len - numlen) + String(num + 1); }
}

add('0078') // '0079'
add('0099') // '00000'

fiddle

Well you could try first turning the string into an integer then incrementing by one then returning the string back as follows:

function incrementString(string){
    var number = parseInt(string);
    number++;
    return number.toString();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top