kbala-ami / invoice-number

Generate invoice number sequentially
MIT License
13 stars 5 forks source link

console.log(InvoiceNumber.next('99')); returns 00 #3

Open RogerEdwinKwesi opened 3 months ago

RogerEdwinKwesi commented 3 months ago

Noticed a bug in the alphaNumericIncrementer function

console.log(InvoiceNumber.next('99')); //00 console.log(InvoiceNumber.next('999')); //000

here is a fix for it:

private static alphaNumericIncrementer(str: string): string { if (!str || str.length === 0) throw new Error('str cannot be empty');

let invNum = str.replace(/([^a-z0-9]+)/gi, '').toUpperCase();
let incremented = '';
let carry = true;

for (let i = invNum.length - 1; i >= 0; i--) {
  let char = invNum[i];
  if (carry) {
    if (char === '9') {
      incremented = '0' + incremented;
    } else if (char === 'Z') {
      incremented = 'A' + incremented;
    } else {
      char = String.fromCharCode(char.charCodeAt(0) + 1);
      incremented = char + incremented;
      carry = false;
    }
  } else {
    incremented = char + incremented;
  }
}

if (carry) {
  incremented = '1' + incremented;
}

return incremented;

}

kbala-ami commented 3 months ago

@RogerEdwinKwesi it will only increment within format. The given alphanumerical value is not only the starting number but it is also the format of the output.