1 // mr.js
  2 
  3 MR = {};
  4 
  5 MR.init = function(){
  6     $max = 0;
  7     $arr = [];
  8     emit = MR.emit;
  9     $numEmits = 0;
 10     $numReduces = 0;
 11     $numReducesToDB = 0;
 12     gc(); // this is just so that keep memory size sane
 13 }
 14 
 15 MR.cleanup = function(){
 16     MR.init();
 17     gc();
 18 }
 19 
 20 MR.emit = function(k,v){
 21     $numEmits++;
 22     var num = get_num( k );
 23     var data = $arr[num];
 24     if ( ! data ){
 25         data = { key : k , values : [] };
 26         $arr[num] = data;
 27     }
 28     data.values.push( v );
 29     $max = Math.max( $max , data.values.length );
 30 }
 31 
 32 MR.doReduce = function( useDB ){
 33     $numReduces++;
 34     if ( useDB )
 35         $numReducesToDB++;
 36     $max = 0;
 37     for ( var i=0; i<$arr.length; i++){
 38         var data = $arr[i];
 39         if ( ! data ) 
 40             continue;
 41         
 42         if ( useDB ){
 43             var x = tempcoll.findOne( { _id : data.key } );
 44             if ( x ){
 45                 data.values.push( x.value );
 46             }
 47         }
 48 
 49         var r = $reduce( data.key , data.values );
 50         if ( r && r.length && r[0] ){ 
 51             data.values = r; 
 52         }
 53         else{ 
 54             data.values = [ r ]; 
 55         }
 56         
 57         $max = Math.max( $max , data.values.length ); 
 58         
 59         if ( useDB ){
 60             if ( data.values.length == 1 ){
 61                 tempcoll.save( { _id : data.key , value : data.values[0] } );
 62             }
 63             else {
 64                 tempcoll.save( { _id : data.key , value : data.values } );
 65             }
 66         }
 67     }
 68 }
 69 
 70 MR.check = function(){                        
 71     if ( $max < 2000 && $arr.length < 1000 ){ 
 72         return 0; 
 73     }
 74     MR.doReduce();
 75     if ( $max < 2000 && $arr.length < 1000 ){ 
 76         return 1;
 77     }
 78     MR.doReduce( true );
 79     $arr = []; 
 80     $max = 0; 
 81     reset_num();
 82     gc();
 83     return 2;
 84 }
 85 
 86