so I'm trying to keep my code clean. To do so I used VS code's built-in code refactoring "move to a new file". As always it couldn't be that easy so everything is not working. When I'm trying to use this method in my Game class, I get an error saying getRandomInt is not a function
. I've seen a dozen StackOverflow threads about this, although none of them could fix my problem. Then I thought it may be just an individual problem, so here I am. Stuck with the same problem for two days...
Game.js:
const { getRandomInt } = require("./index.js");
class Game {
/**
*
* @param {Discord.Message} message
* Passes the message object for the playerId that will be the game Id
*/
constructor(message) {
this.cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
this.playerId = message.author.id;
this.dealerCards = [];
this.playerCards = [];
this.message = message;
}
start() {
console.log(this.cards);
for (let index = 0; index < 2; index++) {
this.playerCards.push(this.cards[getRandomInt(1, this.cards.length)]);
//There's an error saying that getRandomInt is not a function
this.dealerCards.push(this.cards[getRandomInt(1, this.cards.length)]);
}
console.log(this.playerCards);
console.log(this.dealerCards);
this.message.channel.send(`Dealer cards: ${this.dealerCards[0]} ${this.dealerCards[1]}\nPlayer cards ${this.playerCards[0]} ${this.playerCards[1]}`);
}
hit() {
this.playerCards.push(this.cards[getRandomInt(1, this.cards.length)]);
}
}
exports.Game = Game;
index.js (a bit cut down, but it shouldn't make a difference):
const { Game } = require("./Game.js");
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
exports.getRandomInt = getRandomInt;
Is it that hard? It's built into VS code's refactoring system, so I think something is on me.
Circular dependency issue. I don't know why you need to import
Game.js
in yourindex.js
file but removing it will fix the problem. If you still want to useGame.js
in yourindex.js
, there're some approaches for you:exports.Game = function(){};
andexports.getRandomInt = function(){};
at the beginning of modules. It depends on your logic that this approach can fix your problem, you better provide more detail about your code to know your real issue.More info:
How to deal with cyclic dependencies in Node.js
https://nodejs.org/api/modules.html#modules_cycles