forked from jashkenas/coffeescript
-
Notifications
You must be signed in to change notification settings - Fork 5
/
luhn_algorithm.coffee
36 lines (25 loc) · 863 Bytes
/
luhn_algorithm.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Use the Luhn algorithm to validate a numeric identifier, such as credit card
# numbers, national insurance numbers, etc.
# See: http://en.wikipedia.org/wiki/Luhn_algorithm
is_valid_identifier = (identifier) ->
sum = 0
alt = false
for i in [identifier.length - 1..0] by -1
# Get the next digit.
num = parseInt identifier.charAt(i), 10
# If it's not a valid number, abort.
return false if isNaN(num)
# If it's an alternate number...
if alt
num *= 2
num = (num % 10) + 1 if num > 9
# Flip the alternate bit.
alt = !alt
# Add to the rest of the sum.
sum += num
# Determine if it's valid.
sum % 10 is 0
# Tests.
console.log is_valid_identifier("49927398716") is true
console.log is_valid_identifier("4408041234567893") is true
console.log is_valid_identifier("4408041234567890") is false