UNPKG

@adrianperea/genie.js

Version:

A highly flexible, data-agnostic, and UI-independent Genetic Algorithm Library

77 lines (61 loc) 2.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Chromosome = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Chromosome = /*#__PURE__*/function () { function Chromosome(length, generate, mutate) { _classCallCheck(this, Chromosome); if (length === undefined) { throw new Error('length should be defined'); } if (generate === undefined) { throw new Error('generate() should be defined'); } this.length = length; this.generate = generate; if (mutate === undefined) { this.mutate = function (genes, rate) { return genes.map(function (gene) { return Math.random() < rate ? generate() : gene; }); }; } else { this.mutate = mutate; } this.genes = Array(length).fill(null); } _createClass(Chromosome, [{ key: "_init", value: function _init() { this.genes = this.genes.map(this.generate); } }, { key: "setGenes", value: function setGenes(genes) { if (genes.length !== this.length) { throw new Error("Expected genes of length ".concat(this.length, ". Got ").concat(genes.length)); } this.genes = genes; } }, { key: "copyWithGenes", value: function copyWithGenes(genes) { var copy = new Chromosome(this.length, this.generate, this.mutate); copy.setGenes(genes); return copy; } }, { key: "createRandomCopy", value: function createRandomCopy() { var copy = new Chromosome(this.length, this.generate, this.mutate); copy._init(); return copy; } }]); return Chromosome; }(); exports.Chromosome = Chromosome;