<!--
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());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.