Last active
February 8, 2023 10:01
-
-
Save ArtemAvramenko/5889fef42178483f5f6b7b8caf9632d8 to your computer and use it in GitHub Desktop.
Masks email with asterisks/bullets in Node.js
This file contains hidden or 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
/** Masks email, e.g. [email protected] as j•••e@g•••m **/ | |
function maskEmail(email) { | |
function mask(segment) { | |
const hider = '•••'; | |
let result = ''; | |
if (segment) { | |
result = segment[0] + hider; | |
if (segment.length > 2) { | |
result += segment[segment.length - 1]; | |
} | |
} | |
return result; | |
} | |
let i = (email || '').lastIndexOf('@'); | |
if (i < 0) { | |
return mask(email); | |
} | |
return mask(email.substring(0, i)) + '@' + mask(email.substring(i + 1)); | |
} | |
// ==== tests ==== | |
function assert(expected, result) { | |
if (expected === result) { | |
console.log('ok'); | |
} else { | |
console.log(expected + ' - [' + result + ']'); | |
} | |
} | |
assert('', maskEmail(null)); | |
assert('', maskEmail('')); | |
assert('@', maskEmail('@')); | |
assert('t•••t', maskEmail('test')); | |
assert('t•••t@', maskEmail('test@')); | |
assert('t•••', maskEmail('t')); | |
assert('@a•••', maskEmail('@a')); | |
assert('@e•••', maskEmail('@eu')); | |
assert('@c•••m', maskEmail('@com')); | |
assert('a•••@l•••l', maskEmail('a@local')); | |
assert('i•••l@g•••m', maskEmail('invalid@[email protected]')); | |
assert('t•••t@g•••m', maskEmail('[email protected]')); | |
assert('j•••e@m•••t', maskEmail('[email protected]')); | |
assert('j•••e@m•••m', maskEmail('[email protected]')); | |
assert('"•••"@i•••g', maskEmail('"first\"last"@iana.org')); | |
assert('"•••"@i•••g', maskEmail('"first@last"@iana.org')); | |
assert('f•••t@[•••]', maskEmail('first.last@[12.34.56.78]')); | |
assert('"•••"@i•••g', maskEmail('"first"."middle"."last"@iana.org')); | |
assert('y•••s@g•••m', maskEmail('[email protected]')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment