Setup
Implement a function that will hide the last six digits of each phone number. Your function should be able to understand the separators for US numbers. Phone numbers can be separated by spaces, periods, or hyphens.
Examples
Original: 201-680-0202
Encrypted: `201-6XX-XXXX
Tests
encryptNum("328 6587120")
encryptNum("212-420-0202")
encryptNum("211-458-7851")
This challenge comes from otrebor6 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (20)
JavaScript:
The first
replace
finds the last 6 digits, with or without trailing separators.The resulting match undergoes another
replace
call to substitute any digits for X's.The first expression can also be relaxed to allow any separators:
/(\d[^\d]?){6}$/
, or even any number of separators:/(\d[^\d]*){6}$/
.This is neat
Winner
Javascript
This only works if you're expecting a certain value. Output would be weird otherwise.
Yeah, but the data validation is not required in this challange.
True, but it does expect the tests to all pass still, which they won't with that solution
Nice short solution!
If I'm being correct, for the string
"328 6587120"
, the expected output should be"328 6XXXXXX"
.But in your case, the output would be
"328 6XX-XXXX"
.Rust:
Haskell, similar idea to my solution in Ruby
Python, a straightforward approach that would be fast to design and implement without bugs during an interview. It is big-O optimal and easy to understand and refactor.
Elm
Scala,
ONE REGEX TO RULE THEM
Put your separators where you want! I'll find them all.
Dart - not a fan of being creative.
JavaScript
If we want all the phone numbers to have the same format, we could use a regular expression to detect all the digits (assuming that the phone number is correct) and format it accordingly:
If we want to keep the original format (and again, assuming the phone number is correct), another solution would be transforming the string into an array (strings are immutable, an array would be easier to operate), parse the last 6 digits and return its concatenation: