Javascript, w/ psuedo-random short URL


  • 0
    B

    It's always a good idea to separate out your generator from the rest of your functionality, such that you're able to unit test it.

    One thing to note is that there still exists the possibility of a collision, but I'll leave it up to you to ask the interviewer about the level of entropy in the system. For now, this works very well.

    var tinyURLs = {};
    
    /**
     * Encodes a URL to a shortened URL.
     *
     * @param {string} longUrl
     * @return {string}
     */
    var encode = function(longUrl) {
        var newShortURL = generateHash(6);
        tinyURLs[newShortURL] = longUrl;
        return newShortURL;
    };
    
    /**
     * Generates a psuedo-random ID to use for the shortURL.
     *
     * @param {number} length
     * @return {string}
     */
    var generateHash = function(length) {
        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var returnHash = '';
        
        for (var i = 0; i < length; i++) {
            returnHash += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
        }
        
        return returnHash;
    }
    
    /**
     * Decodes a shortened URL to its original URL.
     *
     * @param {string} shortUrl
     * @return {string}
     */
    var decode = function(shortUrl) {
        return tinyURLs[shortUrl];
    };
    
    console.log(decode(encode(url)));
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.