-
-
Save briancavalier/1428135 to your computer and use it in GitHub Desktop.
Coding Challenge: The Luhny Bin http://corner.squareup.com/2011/11/luhny-bin.html
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
function maskCreditCardNumber(value) { | |
function multiply(x, y) { | |
return x * y; | |
} | |
function identyOf(number) { | |
return multiply(number, 1); | |
} | |
function toArrayOfIndividualDigits(value) { | |
return value | |
.split('') | |
.map(identyOf); | |
} | |
function reduce(combine, base, array) { | |
array.forEach(function (element) { | |
base = combine(base, element); | |
}); | |
return base; | |
} | |
function add(x, y) { | |
return x + y; | |
} | |
function sum(numbers, total) { | |
return reduce(add, total, numbers); | |
} | |
function sumOf(func, array) { | |
return reduce(function (total, element) { | |
return sum(func(element), total); | |
}, 0, array); | |
} | |
function individualDigits(number) { | |
var result = []; | |
if (number > 9) { | |
result.push(1); | |
} | |
result.push(number % 10); | |
return result; | |
} | |
function takeEvery(func, array) { | |
return array.filter(func); | |
} | |
function oddIndex(element, index, array) { | |
return index % 2 !== 0; | |
} | |
function evenIndex(element, index, array) { | |
return index % 2 === 0; | |
} | |
function timesTwo(number) { | |
return multiply(number, 2); | |
} | |
function containsValidCharacters(value) { | |
return (/^[\d\s\-]+$/).test(value); | |
} | |
function isValidLength(value) { | |
return value.length >= 14 && value.length <= 16; | |
} | |
function reverseArrayOfIndividualDigits(digits) { | |
var arrayOfDigits = toArrayOfIndividualDigits(digits); | |
return arrayOfDigits.reverse(); | |
} | |
function calculateLuhn(digits) { | |
var fromDigits = reverseArrayOfIndividualDigits(digits); | |
return sum(takeEvery(evenIndex, fromDigits), | |
sumOf(individualDigits, | |
(takeEvery(oddIndex, fromDigits).map(timesTwo)))); | |
} | |
function scrub(value) { | |
return value.split(/\D/).join(''); | |
} | |
function isLuhn(value) { | |
var digits = scrub(value); | |
return containsValidCharacters(value) && | |
isValidLength(digits) && | |
calculateLuhn(digits) % 10 === 0; | |
} | |
function mask(value) { | |
return value.replace(/\d/g, "X"); | |
} | |
return isLuhn(value) ? mask(value) : value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment