Skip to content

Instantly share code, notes, and snippets.

@fujohnwang
Last active August 29, 2015 14:04
Show Gist options
  • Save fujohnwang/f1e0522f74335e25aaf1 to your computer and use it in GitHub Desktop.
Save fujohnwang/f1e0522f74335e25aaf1 to your computer and use it in GitHub Desktop.
credit card number validation
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
}
}
@fujohnwang
Copy link
Author

估计用java循环写,在critical path下性能会更好

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment