r/CodingHelp • u/annathergirl • Oct 31 '21
[Javascript] Coding challenge for a web dev - How to reduce spaghetti code?
5
u/annathergirl Oct 31 '21
A friendly web dev sent me their Pokemon-themed coding challenge for me to try out! It's been a while since I coded but I never really got out of the spaghetti phase. Any ideas how to make the code more efficient?
4
u/phpdevster Professional Coder Nov 01 '21 edited Nov 01 '21
So, a few things:
You're not even using the
pokeobject you're creating. When you need to display a value, you end up calling the variable directly. You can do away with all of thepokeobject code entirely. That is, line 14 and lines 26 through 32 are simply not used and can be removed.You only end up using
name,number,type, andweakness, so I would just eliminate the references toheight,weight, andnextEvolutionif not needed.Since you're basically just taking those values and sticking them into some divs, you could probably do away with variable hand-off entirely and just reference the data directly like this:
data.pokemon[i].name. Just reference it directly where you need it. You could entirely eliminate lines 14 through 32, and then your script becomes a lot simpler.I would try using the fetch API instead of opening a raw XMLHttpRequest as long as you don't care about Internet Explorer support.
If you use the fetch API, when you check for status, return early (e.g
if (!response.ok) return;) instead of wrapping all the success logic. It's usually best to return early.Consider renaming
newPokeand all the other DOM-related variables. What you're dealing with is a DOM element, and the variable name should reflect that.pokemonListContainerElementandpokeNameElementandpokeTypeElementor something to that effect.You don't need the empty elements in your HTML file since you're creating these dynamically in your script. You just need the container you want to append to.
I'm fairly certain you will have a bug in this application if you ever implement a way to refresh the pokemon AJAX request. By appending children to the container element, you will continuously append the same pokemon from the list. You will probably want to immediately call
newPoke.innerHTML = '';(or ideallypokemonListContainerElement.innerHTML = '';to clear it out BEFORE you start appending all of the other pokemon divs. That way if you ever refresh the AJAX call, you get a clean slate every time.Generally the way I'm looking at it is this: if you want to clean up code, you can do it in a couple of ways:
reorganize it e.g. use OOP here, or more functions
reduce it e.g. just strip out unnecessary code and unnecessary work being done by the code
This script is simple enough that option #2 (reduction) is better. No need to over-complicate it. Re-organizing it is not necessary since much of the code itself is not necessary. Re-organizing "useless" code isn't much of an improvement.
In fact I generally advise that any refactoring you do, reduce first, then reorganize if warranted.
Keep it simple.
1
u/annathergirl Nov 01 '21
Wow, thanks a lot, I will go far with these tips! I still have to add height, weight and nextEvolution but I realised that I'd better try to fix this spaghetti first before spending my time to type it all up.
Thanks again.
4
u/Independent-Ad4456 Oct 31 '21 edited Oct 31 '21
// Your other stuff-----------------------------------
if (request.status == 200) {
const data = JSON.parse(request.response);
populateWithPokemon(data.pokemon);
function populateWithPokemon(pokemons) {
const pokemonData = pokemons
.map((pokemon) => {
console.log(pokemon);
return `
<div class="single-pokemon">
<h2 id="name">${pokemon.name}</h2>
<h3 id="number">${pokemon.num}</h3>
<p id="type">${pokemon.type}</p>
<p id="height">${pokemon.height}</p>
<p id="weight">${pokemon.weight}</p>
<p id="weakness">${pokemon.weaknesses}</p>
<p id="nextEvolution">${pokemon.next_evolution}</p>
</div>
`;
})
.join("");
document.querySelector("#pokemon").innerHTML += pokemonData;
}
}
//Your other stuff---------------------------------------You need some checking to make sure nextEvolution exists, but here's my attempt at cleaner code. It does the same thing as yours but in fewer lines. Checking if empty or not is simple, just throw a ternary operator into the string literal.
3
u/annathergirl Oct 31 '21
This solution looks very neat, thank you so much! I haven't coded in 10 months (because of full-time work) so things like mapping I have completed forgotten. Amazing!
1
3
3
u/KevinCupcakes Oct 31 '21 edited Oct 31 '21
Probably better to utilize a forEach.
Rename “data” to pokemonArray.
No need to create name/number/type/etc variables. Just assign poke.property to whatever is in the array.
pokemonArray.forEach(pokemon => {
let poke = {} // should maybe be a “Pokemon” class
poke.name = pokemon[“name”]
…
});2
u/annathergirl Oct 31 '21
Thanks, that's exactly what I was thinking, there must be a solution where I don't have to create all these variables!
13
4
1
u/SlightlyOTT Nov 01 '21
Hard to know without seeing what else is in that inner loop, but the quickest win will probably be to extract a function that takes what you have as data.pokemon as input and does whatever that is doing. So it starts at that for loop. Reducing nesting is often the biggest win in terms of making things clearer. If the for loop is the entire function then you might prefer to extract the function that handles a single data.pokemon but that’s hard to know without seeing the rest of the code.
1
u/annathergirl Nov 01 '21
I have a link to the GitHub repo but it's probably been buried by the comments! Thanks for your input, I'm definitely struggling understanding scopes and reducing nesting.
3
u/prsullivan5 Oct 31 '21 edited Oct 31 '21
Read up on Object destructuring, the JS Array forEach method, and template literals.
const request = new XMLHttpRequest();
const getAlphabeticalNames = (data) => {
data.sort((a, b) => {
const { name: nameA } = a;
const { name: nameB } = b;
return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
});
return data;
};
const createPokemonDiv = pokemon => {
const { name, num, type, height, weight, weaknesses } = pokemon;
const nextEvolution = pokemon.next_evolution ?
pokemon.next_evolution[0].name :
'No more evolutions';
return `
<div class="pokemon">
<h2>Name: ${name}</h2>
<p>Number: ${num}</p>
<p>Type: ${type}</p>
<p>Height: ${height}</p>
<p>Weight: ${weight}</p>
<p>Weakness: ${weaknesses}</p>
<p>Next Evolution: ${nextEvolution}</p>
</div>
`;
};
request.open(
"GET",
"https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json"
);
request.send();
request.onload = () => {
if (request.status === 200) {
const { pokemon } = JSON.parse(request.response);
const parentDiv = document.getElementById("pokemon");
const alphabetizedData = getAlphabeticalNames(pokemon);
alphabetizedData.forEach((poke) => {
const pokemonDiv = createPokemonDiv(poke);
parentDiv.innerHTML += pokemonDiv;
});
}
};2
u/technomancrr Nov 01 '21
A lot of great advice on the thread. Just a small fun thing you could do, create an async function in combination with the fetch function to retrieve your JSON data. async/await works with promises which are becoming increasingly more popular in most JavaScript APIs. So it could be some nice practice for you. I love using http://javascript.info as a reference for most things JS. Also the MDN docs are a great place for examples
2
1
1
u/row_bert Nov 01 '21
Use oop the whole assigning can be done with 1 line by just creating an object.
1
Nov 02 '21
I dont think you need the poke object. You already have the same exact object properties in data.pokemon[i] so there really is no reason to create another object. If you think you still do you could just spread the data.pokemon[i] object into poke like let poke = { …data.pokemon[i] }
0
u/Muted_Row4799 Oct 31 '21
-> Use typescript and interfaces
-> assign with foreach
1
u/annathergirl Oct 31 '21
I haven't learned TypeScript, but will definitely have a look at forEach, thanks !
-1
-7
u/Arag0ld Oct 31 '21
Don't use JavaScript
2
u/annathergirl Oct 31 '21
What would your preferable language for web dev code challenge be then? Bet I could make spagetti out of that as well!
-1
1
u/Askee123 Oct 31 '21
Ok boomer
-1
u/Arag0ld Oct 31 '21
And this comment is relevant... why? JavaScript is a terrible language. I would know, I've written languages. I know what a bad language is.
3
u/Askee123 Oct 31 '21
If you’re incapable of understanding pros and cons of building in any language, you’re a shit software engineer.
Only shit tier engineers blindly mark languages as “good” or “bad” based on their on subjective point of view.
0
u/Arag0ld Nov 01 '21
I know the pros and cons of using JS. I didn't say it was completely useless, did I?
0
2
Oct 31 '21
[removed] — view removed comment
2
u/XoffeeXup Oct 31 '21
an abstract class of 'pokemon' containing all the public variables (name, type etc.), and a few constructors. Then a for loop in Main() that cycles through an array of pokemon data and creates classes for each one. That way you can create multiple instances of each pokemon. something like that?
I'm learning oop atm, and I'm trying to get my head round how to apply it.
33
u/ExtraLargeBarge Oct 31 '21
It looks like you could benefit from having an actual pokemon object. Object-oriented programming is possible in javascript, but it's a bit weird because it uses this structure to do with object prototypes.
Nonetheless, it's perfectly valid, and in this case it would make sense, since you could just replace everything in that for loop with a single line of code - one constructor call.
I recommend you reading up about OOP in javascript and the prototype chain - it might be a bit of a rabbit hole, but I personally think it's very interesting.