xiqe / code-train

前端算法

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Credit Card Mask

xiqe opened this issue · comments

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

maskify("4556364607935616") == "############5616"
maskify(     "64607935616") ==      "#######5616"
maskify(               "1") ==                "1"
maskify(                "") ==                 ""

// "What was the name of your first pet?"
maskify("Skippy")                                   == "##ippy"
maskify("Nananananananananananananananana Batman!") == "####################################man!"

reply

// fn1
function maskify(cc) {
  return cc.length>4?new Array(cc.length-4).fill('#').join('')+cc.substring(cc.length-4):cc;
}

// fn2
function maskify(cc) {
  return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}