Advertisement
radu1986

shuffle object properties

Jun 13th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Count object's properties
  3.  * @param      {{}}  what
  4.  * @returns    {int} count
  5.  * @complexity On
  6.  * @example    Object.count({x:1,y:2}} => 2 (properties)
  7.  */
  8. Object.count = (what) => {
  9.   let count = 0;
  10.   // for each element in the object
  11.   for (let key in what) {
  12.     if (what.hasOwnProperty(key)) {
  13.       // count it :)
  14.       count++;
  15.     }
  16.   }
  17.   // return the total
  18.   return count;
  19. };
  20.  
  21. /**
  22.  * Shuffle object properties, traverses the object one key,value pair at a time several times
  23.  * @param      {{}} what
  24.  * @returns    {{}} output
  25.  * @complexity Onlogn
  26.  * @example    Object.shuffle({x:1,y:2}} => {y:2,x:1} OR {x:1,y:2} random on each run
  27.  */
  28. Object.shuffle = (what) => {
  29.   // need a clone to make sure I don't affect the original object
  30.   const clone  = _.clone(what);       // @see underscore.js
  31.   let   count  = Object.count(clone);
  32.   const output = {};
  33.   // for as many elements in the object
  34.   for (let i = 0, l = count; i < l; i++) {
  35.     // pick a random position, using the object's current state (property count)
  36.     const rand   = Math.floor(Math.random() * count);
  37.     let   pos    = 0;
  38.     // for each element
  39.     for (let key in clone) {
  40.       if (clone.hasOwnProperty(key)) {
  41.         // if random one found
  42.         if (rand === pos) {
  43.           // pick it && move it (copy + delete)
  44.           output[key] = clone[key];               // copy
  45.           // delete the clone's property
  46.           delete clone[key];                      // delete
  47.           // the clone object is smaller, affects the random
  48.           count--;
  49.           break;
  50.         }
  51.         // move on | to the next position in the object
  52.         pos++;
  53.       }
  54.     }
  55.   }
  56.   // return the randomized object
  57.   return output;
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement