Lajos Arpad Lajos Arpad - 3 months ago 18
Javascript Question

How to implement a general set randomizer?

Let us suppose that I intend to implement a randomization functionality, like this:

function Randomizer() {
//Get random member name of object
Object.prototype.getRandomKey = function() {
var keys = Object.keys(this);
return keys[Math.floor(Math.random() * keys.length)];
};
//Get random member value of object
Object.prototype.getRandomElement = function() {
return this[this.getRandomKey()];
};
//Get random index of array
Array.prototype.getRandomKey = function() {
return Math.floor(Math.random() * this.length);
};
//Get random element of array
Array.prototype.getRandomElement = function() {
return this[this.getRandomKey()];
};
//Get random return key of function result
Function.prototype.getRandomKey = function() {
var result = this.apply(this, arguments);
return result && result.getRandomKey();
};
//Get random return member of function result
Function.prototype.getRandomElement = function() {
var result = this.apply(this, arguments);
return result && result.getRandomElement(result.getRandomKey());
};
//Get random element name of what if supported
Randomizer.getRandomKey = function(what) {
if ((!what) || (["undefined", "number", "boolean"].indexOf(typeof what) >= 0)) {
//unsupported
} else if (typeof what !== "function") {
return what.getRandomKey(arguments);
} else {
return Randomizer.getRandomKey(what.apply(this, arguments));
}
};
//Get random element value of what if supported
Randomizer.getRandomElement = function(what) {
if ((!what) || (["undefined", "number", "boolean"].indexOf(typeof what) >= 0)) {
//unsupported
} else if (typeof what !== "function") {
return what.getRandomElement(arguments);
} else {
return Randomizer.getRandomElement(what.apply(this, arguments));
}
};
}


This is how I initialize it

Randomizer();


Usage example

function lorem(b, a) {
return a.substring(1);
}
Randomizer.getRandomElement(lorem, "abcde");


My question is as follows: How can I modify
Randomizer.getRandomKey
and
Randomizer.getRandomElement
so that I can avoid defining a
b
parameter in
lorem
which essentially is the
lorem
object itself at the
getRandomElement
call? Can I do something with the
arguments
object before calling
apply
to get rid of its very first element and pass the arguments after that?

Answer

Can I do something with the arguments object before calling apply to get rid of its very first element and pass the arguments after that?

Yes, slice does that:

var slice = Array.prototype.slice;
….apply(this, slice.call(arguments, 1))