JSFiddle - React, Tailwind, and code Playground

by Mark McFadden

HTML

<!--
Implement the following methods:
Object.prototype.random(): returns randomly one of the values of the object.
For example:

var obj = {
    a: 1,
    b: {
        x: 2,
        y: 3
    },
    c: {
        z: {
            q: 4
        }
    }
};

obj.random(); //returns 1 or 2 or 3 or 4. All values have the same probability to be returned

obj = {};

obj.random(); //returns undefined
---
Object.prototype.toRandomArray(): returns an array of the random values.
For example,

var obj = {
    a: 1,
    b: {
        x: 2,
        y: 3
    },
    c: {
        z: {
            q: 4
        }
    }
};

obj.toRandomArray(); //returns a random permutation of [1, 2, 3, 4]

obj = {};

obj.toRandomArray(); //returns []
-->

JavaScript

var obj = {
    a: 1,
    b: {
        x: 2,
        y: 3
    },
    c: {
        z: {
            q: 4
        }
    }
};

var emptyObj = {};

//helper methods
function toArray(objInput) {
  var result = [];
  for (var prop in objInput) {
    var value = objInput[prop];
      if(typeof value !== "function"){
        if (typeof value === 'object') {
           result.push(toArray(value));
        } else {
            result.push(value);
        }
      }
  }
  return result;
}

var arrResult = [];
function iterArray(arr){
        if(arr instanceof Array){
            //console.log("Length: " + arr.length);
            //console.log(arr);
            for(var key in arr) {
                if (arr.hasOwnProperty(key)) {
                    //console.log(arr[key]);
                    iterArray(arr[key]);
                }
            }
        }else{
            arrResult.push(arr);
            //console.log(arr);
        }

   return arrResult;
}

//end helper methods

Object.prototype.random = function(){
    if(toArray(this).length > 2){//2 for the functions in the opject
        return Math.floor(Math.random()*(toArray(this).length + 1) +1);
    }else{
        return undefined;   
    }
};

Object.prototype.toRandomArray = function(){
    var resultArray = toArray(this);
    return iterArray(resultArray);
};

//test

console.log(obj.random());
console.log(emptyObj.random());

console.log(obj.toRandomArray());