Page 83 - JavaScript
P. 83

}

         // simulate weighted dice where 6 is twice as likely as any other face
         // using multiples of likelihood
         console.log("Rolled a "+(simulateEvent([1,1,1,1,1,2])+1));  // Rolled a 1

         // using probabilities
         console.log("Rolled a "+(simulateEvent([1/7,1/7,1/7,1/7,1/7,2/7])+1));  // Rolled a 6


        As you probably noticed, these functions return an index, so you could have more descriptive
        outcomes stored in an array. Here's an example.


         var rewards = ["gold coin","silver coin","diamond","god sword"];
         var likelihoods = [5,9,1,0];
         // least likely to get a god sword (0/15 = 0%, never),
         // most likely to get a silver coin (9/15 = 60%, more than half the time)

         // simulate event, log reward
         console.log("You get a "+rewards[simulateEvent(likelihoods)]);  // You get a silver coin


        Little / Big endian for typed arrays when using bitwise operators


        To detect the endian of the device


         var isLittleEndian = true;
         (()=>{
             var buf = new ArrayBuffer(4);
             var buf8 = new Uint8ClampedArray(buf);
             var data = new Uint32Array(buf);
             data[0] = 0x0F000000;
             if(buf8[0] === 0x0f){
                 isLittleEndian = false;
             }
         })();


        Little-Endian stores most significant bytes from right to left.

        Big-Endian stores most significant bytes from left to right.


         var myNum = 0x11223344 | 0;  // 32 bit signed integer
         var buf = new ArrayBuffer(4);
         var data8 = new Uint8ClampedArray(buf);
         var data32 = new Uint32Array(buf);
         data32[0] = myNum; // store number in 32Bit array


        If the system uses Little-Endian, then the 8bit byte values will be


         console.log(data8[0].toString(16)); // 0x44
         console.log(data8[1].toString(16)); // 0x33
         console.log(data8[2].toString(16)); // 0x22
         console.log(data8[3].toString(16)); // 0x11


        If the system uses Big-Endian, then the 8bit byte values will be




        https://riptutorial.com/                                                                               40
   78   79   80   81   82   83   84   85   86   87   88