Last active
August 29, 2015 14:03
-
-
Save advantis/bb1d3e71e1ec169dcb3c to your computer and use it in GitHub Desktop.
Functional Luhn algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func isLuhnValid(number: String) -> Bool { | |
let asciiOffset: UInt8 = 48 | |
let convert: (UInt8) -> (UInt8) = { | |
let n = $0 * 2 | |
return n > 9 ? n - 9 : n | |
} | |
let digits = Array(number.utf8).reverse().map{$0 - asciiOffset} | |
let indices = Array(0..digits.count) | |
let evens = indices.filter{$0 & 1 == 0}.map{digits[$0]} | |
let odds = indices.filter{$0 & 1 == 1}.map{digits[$0]}.map(convert) | |
let sum = (evens + odds).reduce(0, +) | |
return sum % 10 == 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment