-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluhn-validator.coffee
48 lines (37 loc) · 1.43 KB
/
luhn-validator.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
37
38
39
40
41
42
43
44
45
46
47
48
getNumeric = (input) ->
string = input.toString()
return string.replace /\D/g, '' # Remove non-digits
getCharactersByOffset = (string, offset = 0) ->
arr = string.split ''
arr.reverse()
characters = []
for c, index in arr by 2
characters.push arr[index+offset]*1
return characters # returns an Array
sum = (arr) ->
# returns a Number
return arr.reduce (cumulation, thisNumber) -> cumulation + thisNumber
sumTwoDigits = (number) ->
splitNumber = number.toString().split ''
totalForThisNumber = 0
for singleNumber in splitNumber
totalForThisNumber += parseInt singleNumber, 10
return totalForThisNumber # returns a Number
doubleThenSum = (arr) ->
total = 0
for d in arr
doubled = d*2
total += (sumTwoDigits doubled)
return total # returns a Number
validateLuhnChecksum = (cardNumber) ->
digits = getNumeric cardNumber
oddDigits = getCharactersByOffset digits
evenDigits = getCharactersByOffset digits, 1
checksum = (sum(oddDigits)) + (doubleThenSum(evenDigits))
return checksum % 10 is 0 # returns True or False
console.log 'invalid example', validateLuhnChecksum '4552 7204 1224 5677'
console.log 'valid example', validateLuhnChecksum '4552 7204 1234 5677'
console.log 'valid', validateLuhnChecksum '1111111111111117'
console.log 'valid', validateLuhnChecksum '1111222233334444'
console.log 'valid', validateLuhnChecksum '1234567812341679'
console.log 'valid', validateLuhnChecksum '4408041234567893'