Skip to content
Myr

Merge pull request #157 from polemius/genetic_algorithm

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Reduce url.js size using genetic algorithm

authored by Andrey Sitnik · committed by GitHub · parents 13e3c44, 1461271 · Browse files · 7 files+125 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+125 added−7 removed

  • tests:+112 added−0 removed
  • other:+13 added−7 removed

7 files+125 added−7 removed

modified:async/index.browser.js+1 added-1 removed
modified:non-secure/index.js+1 added-1 removed
added:test/alphabet-genetic.js+112 added
1let spawnSync = require('child_process').spawnSync2let chalk = require('chalk')3let path = require('path')4let fs = require('fs')5let geneticAlgorithmConstructor = require('geneticalgorithm')6let gzipSize = require('gzip-size')78if (!process.argv[2]) {9 process.stderr.write(chalk.red('Pass a file with alphabet as argument\n'))10 process.exit(1)11}1213let input = path.join(process.cwd(), process.argv[2])14let output = path.join(__dirname, '..', 'compiled.js')1516spawnSync('npx', ['webpack', '--mode', 'production', '--output', output, input])17let js = fs.readFileSync(output).toString()18fs.unlinkSync(output)1920let match = js.match(/[A-Za-z0-9-_]{30,}/)21if (!match) {22 process.stderr.write(chalk.red('Alphabet was not found\n'))23 process.exit(1)24}25let alphabet = match[0]2627function mutationFunction (phenotype) {28 let i = Math.floor(Math.random() * phenotype.alphabet.length)29 let j = Math.floor(Math.random() * phenotype.alphabet.length)3031 return {32 alphabet: swapChars(phenotype.alphabet, i, j)33 }34}3536function swapChars (str, index1, index2) {37 let l = index1 < index2 ? index1 : index238 let h = index1 > index2 ? index1 : index239 return str.substring(0, l) +40 str[h] +41 str.substring(l + 1, h) +42 str[l] +43 str.substring(h + 1, str.length)44}4546function crossoverFunction (phenotypeA, phenotypeB) {47 let alphabetA = phenotypeA.alphabet48 let alphabetB = phenotypeB.alphabet49 let indexA =50 Math.floor(Math.random() * alphabetA.length / 2 + alphabetA.length / 2)51 let indexB =52 Math.floor(Math.random() + alphabetA.length / 2)53 let newStrA = alphabetA.substring(indexA, alphabetA.length)54 let newStrB = alphabetB.substring(0, indexB)5556 return [57 { alphabet: addMissingCharacter(newStrA, alphabetB) },58 { alphabet: addMissingCharacter(newStrB, alphabetA) }59 ]60}6162function addMissingCharacter (str, proto) {63 let newStr = str64 for (let i = 0; i < proto.length; i++) {65 if (str.indexOf(proto[i]) === -1) {66 newStr += proto[i]67 }68 }69 return newStr70}7172function fitnessFunction (phenotype) {73 let file = js.replace(/[A-Za-z0-9-_]{30,}/, phenotype.alphabet)74 let size = gzipSize.sync(file)75 console.log(size, phenotype.alphabet)76 return -1 * size77}7879function sameAlphabet (a, b) {80 let ua = a.split('').sort().join('')81 let ub = b.split('').sort().join('')82 for (let i = 0; i < ua.length; i++) {83 if (ua[i] !== ub[i]) {84 return false85 }86 }87 return true88}8990const firstPhenotype = { alphabet }9192const geneticAlgorithm = geneticAlgorithmConstructor({93 mutationFunction,94 crossoverFunction,95 fitnessFunction,96 population: [firstPhenotype],97 populationSize: 500098})99100console.log('Starting with:', firstPhenotype.alphabet)101for (let i = 0; i < 100; i++) {102 geneticAlgorithm.evolve()103}104const best = geneticAlgorithm.best()105console.log('Finished with:', best.alphabet)106const isSame = sameAlphabet(firstPhenotype.alphabet, best.alphabet)107console.log('Same set of characters:',108 isSame ? chalk.green('true') : chalk.red('false'))109console.log(chalk.green('Size new string:',110 gzipSize.sync(js.replace(/[A-Za-z0-9-_]{30,}/, best.alphabet))))111console.log(chalk.yellow('Size old string:',112 gzipSize.sync(js.replace(/[A-Za-z0-9-_]{30,}/, firstPhenotype.alphabet))))
modified:index.browser.js+1 added-1 removed
modified:package.json+4 added-3 removed
48 unmodified lines
49 "eslint-plugin-promise": "^4.2.1",50 "eslint-plugin-security": "^1.4.0",51 "eslint-plugin-standard": "^4.0.1",52 "eslint-plugin-unicorn": "^12.1.0",53 "geneticalgorithm": "^0.3.6",54 "gzip-size": "^5.1.1",55 "husky": "^3.0.9",56 "jest": "^24.9.0",57 "lint-staged": "^9.4.2",
10 unmodified lines
68 },69 "size-limit": [70 {71 "path": "index.js",71 "limit": "139 B"72 "limit": "137 B"73 },74 {75 "path": "generate.js",76 "limit": "170 B"77 },78 {79 "path": "url.js",79 "limit": "64 B"80 "limit": "63 B"81 },82 {83 "path": "non-secure/index.js",83 "limit": "103 B"84 "limit": "102 B"85 },86 {87 "path": "non-secure/generate.js",88 "limit": "45 B"
86 unmodified lines
modified:url.js+1 added-1 removed
modified:yarn.lock+5 added
4382 unmodified lines
4383 string-width "^1.0.1"4384 strip-ansi "^3.0.1"4385 wide-align "^1.1.0"43864387geneticalgorithm@^0.3.6:4388 version "0.3.6"4389 resolved "https://registry.yarnpkg.com/geneticalgorithm/-/geneticalgorithm-0.3.6.tgz#1b35cac9cc6f3e3e65d0da7308b23c98d651546b"4390 integrity sha512-SGO/2OUchkbneUm+Ky2/RDCyqNGkPYR7qNP7FEJbufY69uHhzUy5hA5Xg+4jalEe9nnanJPXGrtx7PsuPUHlcA==43914392get-caller-file@^1.0.1:4393 version "1.0.3"4394 resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a"4395 integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==
6460 unmodified lines