Last active
September 28, 2015 10:38
-
-
Save jaredcacurak/1426203 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 LuhnyBin(creditCard, minLength, maxLength, maskWithChar) { | |
if (this instanceof LuhnyBin) { | |
this.creditCard = creditCard; | |
this.minLength = minLength || 14; | |
this.maxLength = maxLength || 16; | |
this.maskWithChar = maskWithChar || 'X'; | |
this.output = this.process(creditCard); | |
} else { | |
return new LuhnyBin(creditCard, minLength, maxLength, maskWithChar); | |
} | |
} | |
LuhnyBin.prototype.process = function (creditCard) { | |
var scrubbedCreditCard = this.scrub(creditCard); | |
return this.isLuhn(scrubbedCreditCard) | |
? this.mask(creditCard) | |
: creditCard; | |
}; | |
LuhnyBin.prototype.scrub = function (s) { | |
return s.replace(/\D/g, '') | |
.split('') | |
.map(function (element) { | |
return +element; | |
}); | |
}; | |
LuhnyBin.prototype.isLuhn = function (a) { | |
var length = a.length; | |
return length >= this.minLength | |
&& length <= this.maxLength | |
&& this.luhnSum(a) % 10 === 0; | |
}; | |
LuhnyBin.prototype.luhnSum = function (numbers) { | |
var that, parity; | |
that = this; | |
parity = numbers.length % 2; | |
return numbers.reduceRight(function (previousValue, currentValue, index) { | |
var value = (index % 2 === parity) | |
? that.luhns[currentValue] | |
: currentValue; | |
return previousValue + value; | |
}); | |
}; | |
LuhnyBin.prototype.luhns = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]; | |
LuhnyBin.prototype.mask = function (s) { | |
return s.replace(/\d/g, this.maskWithChar); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like it works! I threw it into jsfiddle just to try it out and used the simple 4111... number from the blog post. Overall, I like the abstractions and the code is really clean, and reads well--I actually had no trouble understanding it even before I read the puzzle!
I see a few things you may want to think about:
maskCreditCardNumber
function is called, it will have to create the 19 nested functions, which could be a bit hit ifmaskCreditCardNumber
is used in a tight loop. There are certainly times where nested functions are the way to go (i.e. when they need variables in the closure context), but in this case, I think I'd hoist as many of the utility functions out of there as possible.number >>> 0;
or evenparseInt(number, 10);
will probably be a lot faster than the multiply() function call. Also forscrub()
, I might just doreturn value.replace(/\D/g, '');
Good job ... pretty interesting puzzle, too :)