Skip to content

Instantly share code, notes, and snippets.

@kirill578
Created January 4, 2022 20:26
Show Gist options
  • Select an option

  • Save kirill578/0f92d23065c11cd520e11a2cac8dbf1f to your computer and use it in GitHub Desktop.

Select an option

Save kirill578/0f92d23065c11cd520e11a2cac8dbf1f to your computer and use it in GitHub Desktop.

Revisions

  1. kirill578 created this gist Jan 4, 2022.
    30 changes: 30 additions & 0 deletions double_luhn_validation.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    export const luhn = (value: string) => {
    let nCheck = 0;
    let nDigit = 0;
    let bEven = true;
    const newValue = value.replace(/D/g, '');

    for (let n = newValue.length - 1; n >= 0; n -= 1) {
    const cDigit = newValue.charAt(n);
    nDigit = parseInt(cDigit, 10);

    if (bEven) {
    nDigit *= 2;
    if (nDigit > 9) {
    nDigit -= 9;
    }
    }

    nCheck += nDigit;
    bEven = !bEven;
    }
    return (1000 - nCheck) % 10;
    };

    export const verifyBarcode = (barcode: string) => {
    const originalCode = barcode.slice(1, -2);
    const raw = `A${originalCode}${luhn(originalCode)}${luhn(
    (parseInt(originalCode, 10) + 1).toString()
    )}`;
    return raw === barcode;
    };