vendredi 1 juillet 2016

Failing to reset one of my object property, revealing module pattern

I was trying to solve that problem : http://ift.tt/29aDFLm 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://ift.tt/29guRpN. I manage all of the tests except the 2 last ones (related to reset).

My code in revealing module pattern

nameDb = {};

function Robot () {
  var name = '';

  var reset = function() {
    name = 'new name';
  }

  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 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;

And this is the first failing test

  it('is able to reset the name', function() {
    var originalName = robot.name;
    robot.reset();
    var newName = robot.name;
    expect(newName).toMatch(/^[A-Z]{2}\d{3}$/);
    expect(originalName).not.toEqual(newName);
  });

Which returns Expected 'ZC189' not to equal 'ZC189'(for instance).

I'm not familiar with that pattern so I'm sure there is something I overlooked. Basically, my reset function does nothing, for some reason it's not able to actually set the name var to zero.

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 (or whatever). Then when the name is called again I give a new one (which must be unique to that object instance).

I guess the problem lies somewhere with my IIFE.. which I guess is not really good in a module pattern. Any insights/leads appreciated

Aucun commentaire:

Enregistrer un commentaire