PageRenderTime 22ms CodeModel.GetById 14ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 1ms

/examples/computer_science/luhn_algorithm.coffee

http://github.com/jashkenas/coffee-script
CoffeeScript | 36 lines | 15 code | 11 blank | 10 comment | 4 complexity | 7f62d5af31d3ec9a0803979333ac4e27 MD5 | raw file
 1# Use the Luhn algorithm to validate a numeric identifier, such as credit card
 2# numbers, national insurance numbers, etc.
 3# See: http://en.wikipedia.org/wiki/Luhn_algorithm
 4
 5is_valid_identifier = (identifier) ->
 6
 7  sum = 0
 8  alt = false
 9
10  for c in identifier by -1
11
12    # Get the next digit.
13    num = parseInt c, 10
14
15    # If it's not a valid number, abort.
16    return false if isNaN num
17
18    # If it's an alternate number...
19    if alt
20      num *= 2
21      num = (num % 10) + 1 if num > 9
22
23    # Flip the alternate bit.
24    alt = !alt
25
26    # Add to the rest of the sum.
27    sum += num
28
29  # Determine if it's valid.
30  sum % 10 is 0
31
32
33# Tests.
34console.log is_valid_identifier("49927398716")      is true
35console.log is_valid_identifier("4408041234567893") is true
36console.log is_valid_identifier("4408041234567890") is false