harthur / brain

Simple feed-forward neural network in JavaScript
MIT License
8.01k stars 857 forks source link

suggestion for code refactor #59

Closed dongyuwei closed 7 years ago

dongyuwei commented 9 years ago

see https://github.com/harthur/brain/blob/master/lib/neuralnetwork.js#L373 the toFunction code as beblow:

toFunction: function() {
    var json = this.toJSON();
    // return standalone function that mimics run()
    return new Function("input",
'  var net = ' + JSON.stringify(json) + ';\n\n\
  for (var i = 1; i < net.layers.length; i++) {\n\
    var layer = net.layers[i];\n\
    var output = {};\n\
    \n\
    for (var id in layer) {\n\
      var node = layer[id];\n\
      var sum = node.bias;\n\
      \n\
      for (var iid in node.weights) {\n\
        sum += node.weights[iid] * input[iid];\n\
      }\n\
      output[id] = (1 / (1 + Math.exp(-sum)));\n\
    }\n\
    input = output;\n\
  }\n\
  return output;');
  }

It looks a little dirty, I suggest to use the multiline lib to replace it.

And if you target only at nodejs/iojs platform, we can just use the ECMA6's string template feature, which supports multiline block code, see template_strings

robertleeplummerjr commented 7 years ago

Solved here: https://github.com/harthur-org/brain.js/blame/master/src/neural-network.js#L496 with es6