hanki.dev

Avoid circular dependencies

I had a situation where util.js required state.js, and state.js required util.js:

// util.js
const state = require("./state")
...
module.exports = { utilFunc }

// state.js
const util = require("./util")
...
module.exports = { set, get }

I was first confused to why this doesn't work, but realized that this causes infinite loop. util.js tries to load state.js, which tries to load util.js, which tries to load state.js etc. Here's a cool diagram I draw since you definitely didn't understand this, right?

Circular dependencies causing infinite loop

Honestly I'm not sure how this should be fixed. Since my util function was a simple one-liner I just copied it straight to state.js instead of refactoring everything. Well, at least I learned something new 🤑

#javascript

- 2 toasts