I was trying to solve that problem : http://exercism.io/exercises/javascript/robot-name/readme but I'm stuck on the last requirement. Let me copy the problem
Write a program that manages robot factory settings.
When robots come off the factory floor, they have no name.
The first time you boot them up, a random name is generated, such as RX837 or BC811.
Every once in a while we need to reset a robot to its factory settings, which means that their name gets wiped. The next time you ask, it will respond with a new random name.
The names must be random: they should not follow a predictable sequence. Random names means a risk of collisions. Your solution should not allow the use of the same name twice when avoidable. In some exercism language tracks there are tests to ensure that the same name is never used twice.
This is the test suite : http://exercism.io/exercises/javascript/robot-name. I manage all of the tests except the last ones (related to unique reset).
My code in revealing module pattern
// To avoid duplicates
nameDb = {};
function Robot () {
var name = '';
// Helpers
var randomizeLetter = function() {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charToChose = randomizeNumber(1, 26);
return chars[charToChose - 1];
};
var randomizeNumber = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var nameGenerator = function() {
var min = 100;
var max = 999;
var output = '';
output += randomizeLetter();
output += randomizeLetter();
output += randomizeNumber(min, max);
return output;
};
// Called on reset
var reset = function reset() {
var candidat = nameGenerator();
if (name != '') delete nameDb[this.name];
name = '';
if(candidat in nameDb) {
reset();
return;
} else {
nameDb[candidat] = true;
this.name = candidat;
}
};
// Called immediately
var newRobot = function newRobot() {
var candidat = nameGenerator();
if(candidat in nameDb) {
newRobot();
return;
} else {
nameDb[candidat] = true;
name += candidat;
}
}();
return {
name: name,
reset: reset
};
}
module.exports = Robot;
Which returns expected 9767 to equal 10001'
What I was trying to do is : when the object is first invoked it has a name property. When the reset is called the name property is set to 0 and the corresponding DB entry is deleted. Then when the name is called again I try give a new one with recursion (which must be unique to that object instance). As you can see it doesn't work because the test doesn't returns 10001 unique ids