PageRenderTime 19ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/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. is_valid_identifier = (identifier) ->
  5. sum = 0
  6. alt = false
  7. for c in identifier by -1
  8. # Get the next digit.
  9. num = parseInt c, 10
  10. # If it's not a valid number, abort.
  11. return false if isNaN num
  12. # If it's an alternate number...
  13. if alt
  14. num *= 2
  15. num = (num % 10) + 1 if num > 9
  16. # Flip the alternate bit.
  17. alt = !alt
  18. # Add to the rest of the sum.
  19. sum += num
  20. # Determine if it's valid.
  21. sum % 10 is 0
  22. # Tests.
  23. console.log is_valid_identifier("49927398716") is true
  24. console.log is_valid_identifier("4408041234567893") is true
  25. console.log is_valid_identifier("4408041234567890") is false