-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
38 lines (33 loc) · 1.06 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const urlMap = {};
function generateShortCode() {
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const length = 6;
let shortCode = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
shortCode += charset[randomIndex];
}
return shortCode;
}
function encodeURL(longURL) {
const shortCode = generateShortCode();
urlMap[shortCode] = longURL;
return shortCode;
}
function decodeURL(shortCode) {
return urlMap[shortCode];
}
async function shortURL() {
const longURL = document.getElementById("url").value;
const shortCode = encodeURL(longURL);
document.getElementById('result').innerHTML = `
Shortened URL: <a href="#" onclick="redirectToOriginal('${shortCode}')">https://example.com/${shortCode}</a>`;
}
function redirectToOriginal(shortCode) {
const originalURL = decodeURL(shortCode);
if (originalURL) {
window.location.href = originalURL;
} else {
alert('Original URL not found');
}
}