3 ms·
If anyone is curious about the luhn algorithm, here is one I made in C# from the example in the question: static bool IsValidLuhn(string numbers) { if (number
by 1337Coder 13y ago
If anyone is curious about the luhn algorithm, here is one I made in C# from the example in the question:
static bool IsValidLuhn(string numbers)
{
if (numbers == null)
throw new ArgumentNullException("number", "number must have a value.");
var allNumbers = numbers
.Where((c) => c >= '0' && c <= '9')
.Reverse()
.Select((c, i) => (i % 2 == 1) ? ((Convert.ToInt32(c) - 48) * 2).ToString() : c.ToString());
return allNumbers.Count() > 0 ? allNumbers.Aggregate((x, y) => x + y).Sum((c) => Convert.ToInt32(c) - 48) % 10 == 0 : false;
}
Edit: Can sum one link me to HackerNews markdown?
- bjconlan 13y agoI also did one in javascript (i've requested it be ammended to the accepted response but we'll see how it reviews) anyway here it is: function validateCC(ccNumber) { var ccNumber = ccNumber.replace(/ /g, ''); console.log( /^3[4|7]\d{13}/.test(ccNumber) ? 'AMEX' : /^6011\d{12}/.test(ccNumber) ? 'Discover' : /^5[1-5]\d{14}/.test(ccNumber) ? 'MasterCard' : /^4[\d{12}|\d{15}]/.test(ccNumber) ? 'Visa' : 'Unknown', ccNumber, ccNumber.split('').reverse() .map(function (v, i) { return v * (1 + i % 2) }) .reduce(function (agg, v) { return agg + v; }, '').split('') .reduce(function (agg, v) { return agg + +v; }, 0) % 10 === 0 ? '(valid)' : '(invalid)'); } btw to markup simply append 2 spaces to the front of the newline
- ycombobreaker 13y agoWhile your code may be fine, I find it weird to see functional operations in the same expression as the ASCII code '0' (48). It is a very weird juxtaposition of abstractions.