phpjs
Version:
67 lines (57 loc) • 1.91 kB
Markdown
layout: page
title: "JavaScript mt_rand function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/mt_rand:476
- /functions/view/mt_rand
- /functions/view/476
- /functions/mt_rand:476
- /functions/476
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's mt_rand
{% codeblock math/mt_rand.js lang:js https://raw.github.com/kvz/phpjs/master/functions/math/mt_rand.js raw on github %}
function mt_rand (min, max) {
// From: http://phpjs.org/functions
// + original by: Onno Marsman
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Kongo
// * example 1: mt_rand(1, 1);
// * returns 1: 1
var argc = arguments.length;
if (argc === 0) {
min = 0;
max = 2147483647;
}
else if (argc === 1) {
throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
}
else {
min = parseInt(min, 10);
max = parseInt(max, 10);
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/math/mt_rand.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/math/mt_rand.js)
### Example 1
This code
{% codeblock lang:js example %}
mt_rand(1, 1);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
1
{% endcodeblock %}
### Other PHP functions in the math extension
{% render_partial _includes/custom/math.html %}