ปัญหา
เราจำเป็นต้องเขียนสองฟังก์ชัน JavaScript -
- ฟังก์ชันแรกควรใช้ URL แบบยาวและส่งคืน URL แบบสั้นที่ตรงกับ URL นั้น
- ฟังก์ชันที่สองควรใช้ URL แบบสั้นและเปลี่ยนเส้นทางไปยัง URL เดิม
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const url = 'https://www.google.com/search?client=firefox-b-d&q=google+search';
const obj = {};
const urlShortener = (longURL = '') => {
let shortURL = "short.ly/" + longURL.replace(/[^a-z]/g,'').slice(-4);
if(!obj[shortURL]){
obj[shortURL] = longURL;
};
return shortURL;
}
const urlRedirector = (shortURL = '') => {
return obj[shortURL];
};
const short = urlShortener(url);
const original = urlRedirector(short);
console.log(short);
console.log(original); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
short.ly/arch https://www.google.com/search?client=firefox-b-d&q=google+search