像javascript中的发票号码增量等新手

时间:2015-01-16 11:51:53

标签: javascript

我需要像freshbooks一样创建发票号码递增功能。如何在新书中使用它是增加数字和字母两者。

条件1: 如果我的发票号码是0000012,则应增加到0000013

条件2: 如果我的发票号是000001a,它应该增加到000001b

等等。 关于如何做到这一点的任何想法?


我的尝试:

function replaceCharAt(string, index, character){
  return string.substr(0, index) + character + string.substr(index + character.length)
}

function generateInvoiceNumber(invoiceNumber, useIndex){
  var useIndex = useIndex || invoiceNumber.length - 1;
  var invoiceNumber = invoiceNumber.trim();
  var incrementChar = invoiceNumber[useIndex];
  if(incrementChar == '9' || incrementChar == 'z' || incrementChar == 'Z'){
    if(incrementChar == 9){
      invoiceNumber = replaceCharAt(invoiceNumber, useIndex, '0');
    }
    else{
      invoiceNumber = replaceCharAt(invoiceNumber, useIndex, 'a');
    }
    return generateInvoiceNumber(invoiceNumber, useIndex - 1);
  }
  else{
    var replaceChar = String.fromCharCode(incrementChar.charCodeAt(0) + 1);
    invoiceNumber = replaceCharAt(invoiceNumber, useIndex, replaceChar);
  }
  return invoiceNumber;
}

这确实产生了正确的结果。但我不确定所有条件,是否会挂起事件循环。我会写一些测试并尝试

1 个答案:

答案 0 :(得分:0)

我想我现在运作良好。我已经针对大多数情况对其进行了测试。

module.exports = {
  replaceCharAt: function replaceCharAt(string, index, character){
    var string = string.split('');
    string[index] = character;
    return string.join('');
  },
  generateInvoiceNumber: function generateInvoiceNumber(invoiceNumber, useIndex){
    var invoiceNumber = invoiceNumber.trim();
    if(typeof useIndex === 'undefined' || useIndex === -1 ){
      useIndex = invoiceNumber.length - 1;
    }
    var incrementChar = invoiceNumber[useIndex];
    if(incrementChar == '9' || incrementChar == 'z' || incrementChar == 'Z'){
      if(incrementChar == 9){
        invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, '0');
      }
      else{
        invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, 'a');
      }
      if(useIndex === 0){
        return invoiceNumber = '1'+invoiceNumber;
      }
      return this.generateInvoiceNumber(invoiceNumber, useIndex - 1);
    }
    else{
      var replaceChar = String.fromCharCode(incrementChar.charCodeAt(0) + 1);
      invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, replaceChar);
    }
    return invoiceNumber;
  }
};