Skip to content

Instantly share code, notes, and snippets.

@vontell
Created January 16, 2018 20:07
Show Gist options
  • Save vontell/2bb2b33d5dc6dff4a010d6668c6eefaa to your computer and use it in GitHub Desktop.
Save vontell/2bb2b33d5dc6dff4a010d6668c6eefaa to your computer and use it in GitHub Desktop.
001 Shorten URL
// Predefined constants
const baseDomain = "https://mywebsite.com/"
// Cached global variables
var urlDictionary = {}
/**
* Returns a shortened version of the given `url`, which is saved for later
* retrieval.
* url - The url to shorten
*/
function shortenURL(url) {
// Grab a random word, removing it from the list
// Note that we are splicing the original word list in order to
// efficiently resize the existing array
var randInt = getRandomInt(0, words.length - 1);
var randWord = words.splice(randInt, 1)[0];
// Save the random word --> url mapping
urlDictionary[randWord] = url;
// Return the shortened version of the URL
return baseDomain + randWord;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
* Obtained from https://stackoverflow.com/questions/1527803
* /generating-random-whole-numbers-in-javascript-in-a-specific-range
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment