Ask coding questions

← Back to all posts
Repl Keeps Freezing
Zavexeon (249)

Hiya guys and gals. I'm having a bit of an issue, and I can't figure out what's going on. I have a method within an object, called arrayRoll(). Essentially what this does is calls the helper function multiRoll() a given amount of times, and adds the results to an array. This array should get returned at the end.

But for some reason, the program seems to freeze and I see no output. Is there something wrong with my JS, or is this something with repl.it?

Here's my code:

//script.js

//dieRoller object
//contains all methods for rolling dice
const dieRoller = {

  //randomly selects number from 1 to sides passed
  roll(sides) {
    return Math.ceil(Math.random() * sides);
  },


  //rolls multiple dice and adds the total 
  multiRoll(sides, times) {
    let totalRoll = 0;

    for (i = 0; i < times; i++) {
      totalRoll += this.roll(sides)
    }
    return totalRoll;
  },


  //rolls multiple dice multiple times and adds the results to an array
  arrayRoll(sides, times, items) {
    let rollArray = [];

    for (i = 0; i < items; i++) {
      rollArray.push(this.multiRoll(sides, times));
    }
    console.log(rollArray);
  },

};

console.log(dieRoller.arrayRoll(6, 2, 6)); //expected output is array with 6 random rolls

Any help is greatly appreciated.

Some things to note:
-The multiRoll() method takes two parameters, sides, and times. Basically this just rolls a x-sided dice an x-amount of times and sums the results. This calls upon a helper function, roll() which generates a random number from one to x.
-The arrayRoll() method takes three parameters, sides, times, and items. What this does is it rolls an x-sided dice an x-amount of times and adds the results to array. It does this for the x-amount of items specified.

Commentshotnewtop
vedprad1 (693)

The way that you are creating functions in the object is wrong. Functions in objects should be made like this:

var dieRoller = {
  roll : function (sides) {
    ...
  },
  ...
}

If this answers your question, please check the checkmark on the left side of this message. Thanks and Good Luck!

Zavexeon (249)

@vedprad1 I've done it the other way several times before and it's always worked.

I did try out your suggestion and unfortunately it did not work. I appreciate your time, though.