Last active
August 29, 2015 14:04
-
-
Save fujohnwang/f1e0522f74335e25aaf1 to your computer and use it in GitHub Desktop.
credit card number validation
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
class CreditCardValidator { | |
@BeanProperty | |
var cardNumberLength = 16 | |
def validate(cardNumber: String): Boolean = { | |
val numberString = StringUtils.deleteWhitespace(cardNumber) | |
if (numberString.length != cardNumberLength) return false | |
if (!StringUtils.isNumeric(numberString)) return false | |
val digits = numberString.map(c => java.lang.Byte.valueOf(String.valueOf(c))) | |
val total = digits.zipWithIndex.foldLeft(0)((total, e) => if (e._2 % 2 != 0) total + e._1 else total + doubleFlat(e._1)) | |
if (total % 10 != 0) false else true | |
} | |
def doubleFlat(value: Byte) = { | |
val doubleValue = value << 1 | |
if (doubleValue > 9) doubleValue / 10 + doubleValue % 10 else doubleValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
估计用java循环写,在critical path下性能会更好