2010-01-24 18:59:29 -05:00
|
|
|
# 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
|
|
|
|
|
2010-07-29 00:03:42 -04:00
|
|
|
is_valid_identifier = (identifier) ->
|
2010-01-24 18:59:29 -05:00
|
|
|
|
2010-07-29 00:03:42 -04:00
|
|
|
sum = 0
|
|
|
|
alt = false
|
2010-01-24 18:59:29 -05:00
|
|
|
|
2013-12-09 17:28:34 -05:00
|
|
|
for c in identifier by -1
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# Get the next digit.
|
2013-12-09 17:28:34 -05:00
|
|
|
num = parseInt c, 10
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# If it's not a valid number, abort.
|
2013-12-09 17:28:34 -05:00
|
|
|
return false if isNaN num
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# If it's an alternate number...
|
|
|
|
if alt
|
|
|
|
num *= 2
|
2010-07-29 00:03:42 -04:00
|
|
|
num = (num % 10) + 1 if num > 9
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# Flip the alternate bit.
|
2010-07-29 00:03:42 -04:00
|
|
|
alt = !alt
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# Add to the rest of the sum.
|
|
|
|
sum += num
|
|
|
|
|
|
|
|
# Determine if it's valid.
|
|
|
|
sum % 10 is 0
|
|
|
|
|
|
|
|
|
|
|
|
# Tests.
|
2010-10-24 12:48:42 -04:00
|
|
|
console.log is_valid_identifier("49927398716") is true
|
|
|
|
console.log is_valid_identifier("4408041234567893") is true
|
|
|
|
console.log is_valid_identifier("4408041234567890") is false
|