-
Notifications
You must be signed in to change notification settings - Fork 0
/
credit-card-mask.js
61 lines (51 loc) · 1.9 KB
/
credit-card-mask.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Credit Card Mask
/*
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 '#'.
Examples (input --> output):
"4556364607935616" --> "############5616"
"64607935616" --> "#######5616"
"1" --> "1"
"" --> ""
// "What was the name of your first pet?"
"Skippy" --> "##ippy"
"Nananananananananananananananana Batman!" --> "####################################man!"
*/
// function maskify1(cc){
// // edge cases where str.length < 4\
// if(cc.length < 4) return cc;
// // var for last 4 chars
// let lastFourChars = '';
// // var for result str
// let result = '';
// // for loop init: saving last 4 chars of CC str
// for(let i = cc.length -1; i >= cc.length - 4 ; i--){
// lastFourChars += cc[i];
// };
// for(let i = 0; i < cc.length - 4; i++){
// result += '#';
// };
// // add lastFourChars to result & return
// result = result + lastFourChars.split('').reverse().join('');
// return result;
// };
const maskify = cc => {
if(cc.length < 4) return cc;
let lastFourChars = '';
let result = '';
for(let i = 0; i < cc.length - 4; i++){
result += '#';
};
for(let i = cc.length - 1; i >= cc.length - 4; i--){
lastFourChars += cc[i];
};
result = result + lastFourChars.split('').reverse().join('');
return result;
};
// more concise + alt solution
function maskify(cc) {
return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}
const x = "4556364607935616" // "############5616"
console.log(maskify(x) === "############5616") // true