Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge, Part II

Is this really efficient?

I am still playing with it, but after looking up loads of stuff on jsperf and across google this code runs faster than anything else I have come up with.

Dave McFarland

Edit: I will add the string check later (umm... to prevent "Bob" from being passed, or perhaps warning the user than using Bob in a numerical representation)

/*Functions*/
function getRandomNumberAfterCheck(top,bottom){
  return floor((Math.random() * (top - bottom + 1))) + bottom; 
}
function getRandomNumber(top,bottom) {
  return getRandomNumberAfterCheck(checkInt(top),checkInt(bottom));
}
function checkInt(num) {
  return num !== num ? num : ~~num;
}
function floor(num) { //This will only work for positive numbers....
  return num|0;
}

alert(getRandomNumber('100','98'));

2 Answers

Zoltรกn Holik
Zoltรกn Holik
3,401 Points

Yes it's efficient, but i have a better solution i think :)

function randomNumber(max, min){
        return Math.abs(~~((Math.random() * ( ~~max - ~~min + 1))) +  ~~min);
}

alert(randomNumber('100', '98'));

Test case: http://jsperf.com/javascript-random-test

Yeah I though of a few ways for negative numbers, it turns out this does work for extremely large numbers either... Also I found a few other faster random methods but I cannot get them to work properly.

Always fun to play with though!

wow