@unitio-code/url-shortener
Version:
A simple URL shortening library
73 lines (72 loc) • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createShortUrl = createShortUrl;
exports.decodeUrl = decodeUrl;
const utils_1 = require("./utils");
/**
* Default options for creating a short URL
*/
const DEFAULT_CREATE_OPTIONS = {
...utils_1.DEFAULT_SHORT_URL_OPTIONS,
hashAlgorithm: "djb2",
};
/**
* Creates a short URL from a long URL with customizable options
* @param longUrl - The original long URL to shorten
* @param domain - Domain name for the short URL
* @param options - Optional configuration options
* @returns The shortened URL
*/
function createShortUrl(longUrl, domain, options) {
const opts = {
...DEFAULT_CREATE_OPTIONS,
domain,
...options,
};
let hash;
if (opts.hashAlgorithm === "custom" && opts.customHashFn) {
hash = opts.customHashFn(longUrl);
}
else if (opts.hashAlgorithm === "sdbm") {
hash = 0;
for (let i = 0; i < longUrl.length; i++) {
const char = longUrl.charCodeAt(i);
hash = char + (hash << 6) + (hash << 16) - hash;
}
}
else {
hash = 5381;
for (let i = 0; i < longUrl.length; i++) {
const char = longUrl.charCodeAt(i);
hash = (hash << 5) + hash + char;
}
}
const positiveHash = Math.abs(hash);
(0, utils_1.storeUrlMapping)(positiveHash, longUrl);
return (0, utils_1.buildShortUrl)(positiveHash, opts);
}
/**
* Extracts the short code from a short URL
* @param shortUrl - The short URL
* @returns The extracted short code
*/
function extractShortCode(shortUrl) {
const urlWithoutProtocol = shortUrl.replace(/^https?:\/\//, "");
const parts = urlWithoutProtocol.split("/");
return parts[parts.length - 1];
}
/**
* Decodes a short URL back to its original URL
* @param shortUrl - The shortened URL to decode
* @returns The original URL if found, or undefined if not found
*/
function decodeUrl(shortUrl) {
try {
const shortCode = extractShortCode(shortUrl);
const id = (0, utils_1.decodeShortUrl)(shortCode);
return (0, utils_1.getOriginalUrl)(id);
}
catch (error) {
return undefined;
}
}