Skip to content

Instantly share code, notes, and snippets.

@naden
Forked from 140bytes/LICENSE.txt
Last active December 15, 2015 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naden/5236922 to your computer and use it in GitHub Desktop.
Save naden/5236922 to your computer and use it in GitHub Desktop.
Generate random numbers in a given range in less than 140byt.es
function getRandom(a, b) {
// arguments.length is zero, if a and b are falsy
return !a && !b
?
// we return the result of a default Math.random() call
// and save the result in case we need is later
r = Math.random()
:
(
// wrapped the code in a function for
// byte saving via arguments shortcuts
function(r, a, b) {
// we only deal with int
// it's impossible *g* to detect that 1.0 is a float in javascript
// see my post http://stackoverflow.com/questions/11798903/javascript-casts-floating-point-numbers-to-integers-without-cause
return parseInt(
// shortcut for one argument
!b
?
// we deal with one argument - max value
r * (a + (a < 0 ? -1 : 1))
:
// two arguments - min and max value
a + (r * (b - a + 1))
)
}
)
// r = placeholder for the result of Math.random() see obove
// a = function argument one
// b = function argument two or zero
(r, a, b || 0)
}
function(a,b){return !a&&!b?r=Math.random():(function(r,a,b){return parseInt(!b?r*(a+(a<0?-1:1)):a+(r*(b-a+1)))})(r,a,b||0)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Naden Badalgogtapeh <http://www.naden.de>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "getRandom",
"description": "Generate random numbers in a given range.",
"keywords": [
"number",
"math",
"random",
"140bytes",
"fjavascript"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(a,b){return !a&&!b?r=Math.random():(function(r,a,b){return parseInt(!b?r*(a+(a<0?-1:1)):a+(r*(b-a+1)))})(r,a,b||0)}
var ret = document.getElementById( "ret" );
ret.innerHTML = myFunction();
ret.innerHTML += '<br>' + myFunction(1);
ret.innerHTML += '<br>' + myFunction(-1);
ret.innerHTML += '<br>' + myFunction(7);
ret.innerHTML += '<br>' + myFunction(-7);
ret.innerHTML += '<br>' + myFunction(2, 4);
ret.innerHTML += '<br>' + myFunction(-1, 1);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment