Recursive Unique Random Generator

by Ehsan Ziya

JavaScript

function Random(){
    this.random = Math.random;
    this.ceil = Math.ceil;
    this.floor = Math.floor;
    this.previousf = 0;
    this.previousi = 0;
}

Random.prototype.float = function(min, max){
    return (this.random() * (max - min)) + min;
};
Random.prototype.uniquef = function(min, max){
    var newRandom = this.float(min, max);
    if(newRandom == this.previousf){
        return this.unique(min, max);
    } else {
        this.previousf = newRandom;
        return newRandom;
    }
};

Random.prototype.int = function(min, max){
    return this.floor(this.float(min, max));
};

Random.prototype.uniquei = function(min, max){
    var newRandom = this.int(min, max);
    if(newRandom == this.previousi){
        return this.uniquei(min, max);
    } else {
        this.previousi = newRandom;
        return newRandom;
    }
};

var r = new Random();

setInterval(function(){
    var uniqueFloat = r.uniquef(-5, 5);
    var uniqueInt = r.uniquei(-5, 5);
}, 50);