Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Count object's properties
- * @param {{}} what
- * @returns {int} count
- * @complexity On
- * @example Object.count({x:1,y:2}} => 2 (properties)
- */
- Object.count = (what) => {
- let count = 0;
- // for each element in the object
- for (let key in what) {
- if (what.hasOwnProperty(key)) {
- // count it :)
- count++;
- }
- }
- // return the total
- return count;
- };
- /**
- * Shuffle object properties, traverses the object one key,value pair at a time several times
- * @param {{}} what
- * @returns {{}} output
- * @complexity Onlogn
- * @example Object.shuffle({x:1,y:2}} => {y:2,x:1} OR {x:1,y:2} random on each run
- */
- Object.shuffle = (what) => {
- // need a clone to make sure I don't affect the original object
- const clone = _.clone(what); // @see underscore.js
- let count = Object.count(clone);
- const output = {};
- // for as many elements in the object
- for (let i = 0, l = count; i < l; i++) {
- // pick a random position, using the object's current state (property count)
- const rand = Math.floor(Math.random() * count);
- let pos = 0;
- // for each element
- for (let key in clone) {
- if (clone.hasOwnProperty(key)) {
- // if random one found
- if (rand === pos) {
- // pick it && move it (copy + delete)
- output[key] = clone[key]; // copy
- // delete the clone's property
- delete clone[key]; // delete
- // the clone object is smaller, affects the random
- count--;
- break;
- }
- // move on | to the next position in the object
- pos++;
- }
- }
- }
- // return the randomized object
- return output;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement