Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การเขียนฟังก์ชันย่อ URL แบบกำหนดเองใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript 2 ฟังก์ชัน:

  • ฟังก์ชันแรกรับ URL ยาว และคืนค่า URL สั้นที่สอดคล้อง
  • ฟังก์ชันที่สองรับ URL สั้น และ redirect ไปยัง 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

คำอธิบายเพิ่มเติม

ตัวอย่างนี้เป็นการสาธิตหลักการพื้นฐาน จริงๆ ควรใช้ hash function (เช่น base62 encoding ของ auto-increment ID) และเก็บใน database ไม่ใช่ object ในหน่วยความจำ เพื่อความทนทานและป้องกันการชน (collision)