We’re going to refactor some pieces of codes
// Unrefactored code
const URLstore = [];
function makeShort(URL) {
const rndName = Math.random().toString(36).substring(2);
URLstore.push({[rndName]: URL});
return rndName;
}
function getLong(shortURL) {
for (let i = 0; i < URLstore.length; i++) {
if (URLstore[i].hasOwnProperty(shortURL) !== false) {
return URLstore[i][shortURL];
}
}
}
Problem: what happens if getLong is called with a short URL that isn’t in the store? Nothing is explicitly returned so undefined will be returned. Since we’re not sure how we’re going to handle that, let’s be explicit and throw an error so that problems can be spotted during development.
// Refactored code
const URLstore = new Map(); // Change this to a Map
function makeShort(URL) {
const rndName = Math.random().toString(36).substring(2);
// Place the short URL into the Map as the key with the long URL as the value
URLstore.set(rndName, URL);
return rndName;
}
function getLong(shortURL) {
// Leave the function early to avoid an unnecessary else statement
if (URLstore.has(shortURL) === false) {
throw 'Not in URLstore!';
}
return URLstore.get(shortURL); // Get the long URL out of the Map
}
It’s important to get your code right the first time because in many businesses there isn’t much value in refactoring. Or at least, it’s hard to convince stakeholders that eventually uncared for codebases will grind productivity to a halt.
Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.