JavaScript‎ > ‎

Luhn validation

I found this code, at my collage,  It's not my code.

// Luhn algorithm validator, by Avraham Plotnitzky. (aviplot at gmail)
String.prototype.luhnCheck = function()
{
    var luhnArr = [[0,2,4,6,8,1,3,5,7,9],[0,1,2,3,4,5,6,7,8,9]], sum = 0;
    this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){
        sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ];
    });
    return (sum%10 === 0) && (sum > 0);
};

// Luhn algorithm producer, by Avraham Plotnitzky. (aviplot at gmail)
String.prototype.luhnGet = function()
{
    var luhnArr = [[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]], sum = 0;
    this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){
        sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]
    });
    return this + ((10 - sum%10)%10);
};

**********************************************************************
And improved version, for fast reaction, in case this is matter.
**********************************************************************

// Luhn algorithm validator, by Avraham Plotnitzky. (aviplot at gmail)
function luhnCheckFast1(Luhn)
{
    var ca, sum = 0, mul = 1;
    var len = Luhn.length;
    while (len--)
    {
        ca = parseInt(Luhn.charAt(len),10) * mul;
        sum += ca - (ca>9)*9;// sum += ca - (-(ca>9))|9
        // 1 <--> 2 toggle.
        mul ^= 3; // (mul = 3 - mul);
    };
    return (sum%10 === 0) && (sum > 0);
};

// Luhn algorithm validator, by Avraham Plotnitzky. (aviplot at gmail)
function luhnCheckFast2(Luhn)
{                                 
    var ca, sum = 0, mul = 0;
    var len = this.length;
    while (len--)
    {
        ca = parseInt(this.charAt(len),10) << mul;
        sum += ca - (ca>9)*9; // sum += ca - (-(ca>9))|9
        // 1 <--> 0 toggle.
        mul ^= 1; // mul = 1 - mul;
    };
    return (sum%10 === 0) && (sum > 0);
};



ċ
luhn.js
(1k)
Inco Gnito,
Feb 28, 2011, 8:15 AM
Comments