@fadhilradh
Posted
Hi Daniel,
First off I’d say that your result is great! It looks exactly like the design and works well. Well done!
I have taken look at your source code and I have a suggestion for your question about how to refactor your main.js file.
First, I see a lot of code inside your updateBill
function and it’s not very readable. What you can do is you can extract every code inside an if or else if to another function. Example :
Instead of :
if(foo) {
…foocode..
} else if (bar)
…barcode…
{
You can write as :
if (foo) {
doFoo()
} else if (bar) {
doBar()
}
This is more readable for the one who will read your code (your co-workers) and cleaner as it follow the principle of one function should only do one thing. Also, make sure your function name is meaningful and should be a verb.
Secondly, you can further improve your code by separating your code into several files, grouping similar functions and variables inside a file and making use of import
and export
statements.
For example you can split into three files : main.js for storing your global variables, updateBill.js for updating functions and utils.js for other functions. Then, you can export function to be available in another file. For example :
// updateBill.js
export function updateBill() {
…doAwesomeThings()
}
// main.js
import { updateBill } from “./updateBill.js”
updateBill()
You can do this for every other function and group similar functions in one js file.
Hope it helps and good luck Daniel !
Marked as helpful
@DanoSvK
Posted
@fadhilradh These are great advices. Thanks. I will definitely try to refactor this code.
@fadhilradh
Posted
@DanoSvK you are welcome Daniel. Good luck !
@fadhilradh
Posted
@DanoSvK Hi Daniel, sorry I forgot to mention, you need to make change to your HTML file : Add type="module"
to your link to main.js file. This will make your JS files able to import and export function and variables to each other. Otherwise there will be an error.
@DanoSvK
Posted
@fadhilradh Thanks man, I appreciate your time and effort 👍
@fadhilradh
Posted
@DanoSvK It's nothing man, glad to help !