From 4c5973923d65c7539dd5c9fe8a7921b7db13b1ec Mon Sep 17 00:00:00 2001 From: TK Date: Fri, 26 Apr 2024 08:22:52 -0300 Subject: [PATCH] * --- .../frontend/react/components/phone-input.js | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 coding_interviews/frontend/react/components/phone-input.js diff --git a/coding_interviews/frontend/react/components/phone-input.js b/coding_interviews/frontend/react/components/phone-input.js new file mode 100644 index 0000000..0a06969 --- /dev/null +++ b/coding_interviews/frontend/react/components/phone-input.js @@ -0,0 +1,72 @@ +import React, { useState } from 'react'; + +export default function PhoneInput() { + const [phoneNumber, setPhoneNumber] = useState(''); + const isPhoneNumberComplete = phoneNumber.length === 14; + + const formatAddingNumber = (key) => { + if (phoneNumber.length === 0) { + return `(${key}`; + } + + if (phoneNumber.length === 4) { + return `${phoneNumber}) ${key}`; + } + + if (phoneNumber.length === 9) { + return `${phoneNumber}-${key}`; + } + + if (isPhoneNumberComplete) { + return phoneNumber; + } + + return phoneNumber + key; + }; + + const formatRemovingNumber = () => { + if (phoneNumber.length === 2) { + return ''; + } + + if (phoneNumber.length === 7) { + return phoneNumber.slice(0, phoneNumber.length - 3); + } + + if (phoneNumber.length === 11) { + return phoneNumber.slice(0, phoneNumber.length - 2); + } + + return phoneNumber.slice(0, phoneNumber.length - 1); + }; + + const handleOnKeyDown = (e) => { + const isNumber = /^[0-9]$/i.test(e.key); + + if (isNumber) { + setPhoneNumber(formatAddingNumber(e.key)); + } + + if (['Backspace', 'Delete'].includes(e.key)) { + setPhoneNumber(formatRemovingNumber()); + } + }; + + const handleOnClick = (e) => { + setPhoneNumber(''); + }; + + return ( + <> + + + + ); +}