概率的可配置化

function randomInProbability( weights ){
  if( arguments.length > 1 ){
    weights = [].slice.call( arguments );
  }

  var total, current = 0, parts = [],
      i = 0, l = weights.length;

  total = weights.reduce ? weights.reduce( function( a, b ){
    return a + b;
  } ) : eval( weights.join( '+' ) );

  for( ; i < l; i ++ ){
    current += weights[ i ];
    parts.push( 'if( p < ', current / total, ' ) return ', i / l, ' + n;' );
  }

  return Function( 'var p = Math.random(), n = Math.random() / ' + l + ';' + parts.join( '' ) );
}
var updateRandom = randomInProbability( 0.01, 0.02, 0.09, 1.8, 0.1 );
var objects = [ '登山包', '旅行箱', '移动电源', '谢谢参与', '不中奖' ];
var randomIndex = Math.floor( objects.length * updateRandom() ); 
var object = objects[ randomIndex ];

 

posted @ 2016-06-20 15:25  壁虎漫步.  阅读(203)  评论(0编辑  收藏  举报