DEV Community

Discussion on: Daily Challenge #179 - Hide Phone Numbers

Collapse
 
candidateplanet profile image
lusen / they / them 🏳️‍🌈🥑

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.

def encrypt(phone_num):
  # define some const. easy to refactor into method sig or config elsewhere later
  ENCRYPT_NUMBER = 6
  ENCRYPT_SYMBOL = 'X'

  # we'll return this at the end - reversed and joined.
  encrypted = []
  # count the numbers we encrypt
  counter = 0

  # start at the end and encrypt numbers until we reach ENCRYPT_NUMBER
  for ch in phone_num[::-1]:
    # we're done encrypting so pass everything along
    if counter == ENCRYPT_NUMBER:
      encrypted.append(ch)
      continue

    try:
      # if character is a number, encrypt it
      int(ch)
      counter += 1
      encrypted.append(ENCRYPT_SYMBOL)
    except ValueError:
      # character is not a number so pass it  through
      encrypted.append(ch)

  # return a string in the right order
  return ''.join(encrypted[::-1])

print(encrypt("328 6587120")) # 328 6XXXXXX
print(encrypt("212-420-0202")) # 212-4XX-XXXX
print(encrypt("211-458-7851")) # 211-4XX-XXXX
print(encrypt("211 458 7851")) # 211 4XX XXXX
print(encrypt("2114587851")) # 2114XXXXXX