Reputation: 982
I need a function with certain probability that it will fire, something like:
function broken_fn ( function () { console.log( Math.random() ); }, 33 ) {
// code...
}
for use in simple online game I'm working on...
Upvotes: 1
Views: 188
Reputation: 2167
Here's the way that won't fire the function right away, but you can call it repeatedly to maybe fire (didn't realize this was the intention):
function getMaybeFireFunction (fn, probability) {
return function() {
if (Math.random() < probability) {
fn();
}
};
}
Use:
var fn = getMaybeFireFunction(function() { console.log('hello'); }, .5);
fn();
fn();
Upvotes: 0
Reputation: 2167
How about:
function maybeFire (fn, probability) {
if (Math.random() < probability) {
fn();
}
}
Use it as:
maybeFire(function() { console.log('fired!'); }, .5);
Upvotes: 10
Reputation: 982
function broken_fn( fn, will_fire_probability /* 0 - 100 */ ) {
// #helpers
function slc( args, i1, i2 ) {
return Array.prototype.slice.call( args, i1, i2 );
}
function clumpnum( num, min, max, _default ) {
return ( Object.prototype.toString.call( num ) === "[object Number]" )
? (
( isFinite( num ) )
? ( ( ( num >= min ) && ( num <= max ) ) || ( num = _default ), num )
: _default
)
: _default;
}
function randint( min, max, un ) {
var r;
return ( min === un && max === un ) && ( Math.random() ) ||
(
( max === un ) &&
( max = min, min = 0, r = min + Math.floor( Math.random() * (max - min + 1) ), true ) ||
( r = min + Math.floor( Math.random() * ( max - min + 1 ) ) )
) && r;
}
// code
var
pr = clumpnum( will_fire_probability, 0, 100, 50 ),
args1 = slc( arguments, 2 );
return function () {
var out;
( ( pr == 100 ) || ( randint( 0, 100 ) < pr ) )
&& ( out = fn.apply( this, args1.concat( slc( arguments ) ) ) );
return out;
}
}
var
f1 = broken_fn( function () { console.log( Math.random() ); }, 25 );
f1();
f1();
f1();
f1();
f1();
f1();
f1();
f1();
f1();
f1();
//
// 0.00948742698193461
// 0.3570269207216398
// 0.01068347242658918
//
// ...
//
Upvotes: -5