These are the instructions for the kata I'm working on:
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 '#'.
I'm having a hard time figuring out why this code is able to print out the correct answer
let maskify = cc => console.log('#'.repeat(cc.length - 4) cc.substr(-4));
But the following code only returns "RangeError: Invalid count value at String.repeat ()"
let maskify = cc => {
return '#'.repeat(cc.length - 4) cc.substr(-4);
}
CodePudding user response:
How are you running your function? I ran your function in repl.it with some sample input, and it works fine.
let maskify = cc => {
return '#'.repeat(cc.length - 4) cc.substr(-4);
}
console.log(maskify("abcdefghijklmnop"));
//logs "############mnop"
CodePudding user response:
Both code snippets produce same results. If the parameter length is less than 4, it will error-out.
let maskify = cc => console.log('#'.repeat(cc.length - 4) cc.substr(-4));
maskify('1234123456785678'); // Masks first 12 digits
maskify('12341'); // Masks first digit
maskify('123'); // Invalid count value error
let maskify = cc => {
return '#'.repeat(cc.length - 4) cc.substr(-4);
};
// Same results as previous code
console.log(maskify('1234123456785678')); // Masks first 12 digits
console.log(maskify('12341')); // Masks first digit
console.log(maskify('123')); // Invalid count error
How it works
- First the parameter
cc
needs to be at least 4 chars length (typically, it may be 16 chars length) - The
'#'.repeat()
instructs that the character#
needs to berepeat
-ed. - The parameter sent to
repeat
tells how many times. So,cc.length - 4
indicates that forcc
of 16 chars, there will be 12'#'
repeated - The
'#'
s with the operand on its right - The
cc.substr(-4)
extracts the last 4 characters fromcc
(& this is the operand on the right-side of
Both the snippets do the same logic. The first one logs to the console
; while the second one returns the string.