Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var computeRoll = function(diceAndMods) {
  var numberOfDie = 0,
      sidesOfDie = 0,
      modifier = 0,
      temp,
      result = 0,
      errorMsg = "Requires a string of the format #d#[+-]#",
      regEx = /^(\d+)d(\d+)([+-]\d+)?$/;
  
  if(!regEx.test(diceAndMods)) {
    console.log(errorMsg);
    return result;
  }
  
  temp = regEx.exec(diceAndMods);
  
  numberOfDie = parseInt(temp[1], 10);
  sidesOfDie = parseInt(temp[2], 10);
  
  if(temp[3]) {
    modifier = parseInt(temp[3], 10);
  }
  
  for(var i = 0; i < numberOfDie; i++) {
    result += Math.floor(Math.random() * (sidesOfDie) + 1);
  }
  
  result += modifier;
  
  return result;
};
console.log(computeRoll("4d3"));
console.log(computeRoll("-4d8-1"));
console.log(computeRoll("2d6+3"));
console.log(computeRoll("2d8&3"));
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers