Skip to content

Commit 05f0dac

Browse files
author
Nicholas C. Zakas
committed
Added Luhn algorithm
1 parent 696c3cb commit 05f0dac

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* Luhn algorithm implementation in JavaScript
3+
* Copyright (c) 2009 Nicholas C. Zakas
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
24+
25+
/**
26+
* Uses Luhn algorithm to validate a numeric identifier.
27+
* @param {String} identifier The identifier to validate.
28+
* @return {Boolean} True if the identifier is valid, false if not.
29+
*/
30+
function isValidIdentifier(identifier) {
31+
32+
var sum = 0,
33+
alt = false,
34+
i = identifier.length-1,
35+
num;
36+
37+
while (i >= 0){
38+
39+
//get the next digit
40+
num = parseInt(identifier.charAt(i), 10);
41+
42+
//if it's not a valid number, abort
43+
if (isNaN(num)){
44+
return false;
45+
}
46+
47+
//if it's an alternate number...
48+
if (alt) {
49+
num *= 2;
50+
if (num > 9){
51+
num = (num % 10) + 1;
52+
}
53+
}
54+
55+
//flip the alternate bit
56+
alt = !alt;
57+
58+
//add to the rest of the sum
59+
sum += num;
60+
61+
//go to next digit
62+
i--;
63+
}
64+
65+
//determine if it's valid
66+
return (sum % 10 == 0);
67+
}

0 commit comments

Comments
 (0)