JJ / nodeo

Simple evolutionary algorithm in JavaScript in CommonJS format, for node.js and anything else.
GNU General Public License v3.0
22 stars 6 forks source link

Do methods in nodeo/chromosome.js really need a parameter being the chromosome itself? #21

Closed vrivas closed 8 years ago

vrivas commented 8 years ago

Hi JJ! I'm trying to program a chromosome for nodeo made of floats. I've copied chromosome.js and can't understand why invert or mutate need to be given a chromosome as a parameter. Since they are methods of a chromosome they really don't need that parameter. Or, another solution, put all the methods out of the object, as regular functions (maybe inside a single namespace). I think this would make to save a lot of memory, since now, every object has to be given space for those "methods" that, in fact, are working as external functions.

JJ commented 8 years ago

They are "functors", acting as functions outside an object, and using the "visitor" pattern.

vrivas commented 8 years ago

OK. But I really think that programming it this way makes the objects bigger than necessary.

// Creates a single chromosome. Includes all utility functions
function Chromosome(string,fitness){
    this.string = string;
    this.fitness = fitness;
    this.invert = invert; // This makes every object having this method

implemented, so it should be avoided }

Maybe you should try another solution, that works fine in Javascript:

   // Bit-flips the whole chromosome   
 Chromosome.prototype.invert=function(chromosome) {
      chromosome = chromosome || this;  // This line could be optional
      var inverted='';
      for (var i = 0; i < chromosome.string.length; i ++ ) {
       inverted += chromosome.string.charAt(i).match(/1/)?"0":"1";
     }
    return new Chromosome (inverted);
}

Using Chromosome.prototype the method is available for every object but it's not copied in every object. And using chromosome = chromosome || this; you make it work with the chromosome receiving the message or with any other, as you want to do in your code.

Of course, you can also try this other approach:

 // Bit-flips the whole chromosome 
 Chromosome.invert=function(chromosome) {
     var inverted='';
     for (var i = 0; i < chromosome.string.length; i ++ ) {
        inverted += chromosome.string.charAt(i).match(/1/)?"0":"1";
     }
     return new Chromosome (inverted);
}

So that the method belongs to the class Chromosome, not available to the object

I've tested both approaches in Firefox, so I image they will also work in node.js.

Cheers!

2015-11-28 8:40 GMT+01:00 Juan Julián Merelo Guervós < notifications@github.com>:

They are "functors", acting as functions outside an object, and using the "visitor" pattern.

— Reply to this email directly or view it on GitHub https://github.com/JJ/nodeo/issues/21#issuecomment-160258106.

Victor Manuel Rivas Santos

JJ commented 8 years ago

You are very probably right. I'll take a look and change accordingly.