Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future solutions in a clever and efficient way. I’ve decided that I am going to post my solutions here written in Java, JavaScript and Python for all of my readers to learn! Please let me know if you have any questions.
Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*
Credit Card Masking
Usually when you buy something, you’re asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don’t want that shown on your screen. Instead, we mask it.
Your task is to write a function maskify
, which changes all but the last four characters into '#'
.
Maskify.Maskify("4556364607935616"); // should return "############5616"
Maskify.Maskify("64607935616"); // should return "#######5616"
Maskify.Maskify("1"); // should return "1"
Maskify.Maskify(""); // should return ""
// "What was the name of your first pet?"
Maskify.Maskify("Skippy"); // should return "##ippy"
Maskify.Maskify("Nananananananananananananananana Batman!"); // should return "####################################man!"
JavaScript Solution
function maskify(cc) {
// If length is greater than 4, then we have things to mask
if (cc.length > 4) {
// reverse string
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
// if i < 4, we want to reveal these numbers in our output
if (i < 4) {
newString += reversed[i];
} else {
// otherwise, just hide it
newString += '#';
}
}
// return the reversal of the string to revert it back to original format
return reverse(newString);
} else {
return cc;
}
}
function reverse(str) {
return str.split("").reverse().join("");
}
Python Solution
def maskify(cc):
str = ''
for char in cc[:-4]:
str += '#'
str += cc[-4:]
return str
Java Solution
public class Maskify {
public static String maskify(String str) {
if (str.length() < 4) {
return str;
} else {
String newStr = "";
for (Integer i = 0; i < str.length(); i++) {
if (i >= 4) {
newStr += "#";
}
}
newStr += str.substring(str.length() - 4);
return newStr;
}
}
}