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
Provenance
- Commit
d0495f3- Tree
9516a27- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
GitHub <noreply@github.com>- Parent 1
13e3c44- Parent 2
1461271
7 files changed+125 added−7 removed
modified:async/index.browser.js+1 added-1 removed
2 unmodified lines3456778910116 unmodified lines2 unmodified lines/* * This alphabet uses a-z A-Z 0-9 _- symbols. * Symbols order was changed for better gzip compression. */var url = 'Uint8ArModuleSymbhasOw-012345679BCDEFGHIJKLNPQRTVWXYZ_cfgjkpqvxz'var url = 'IUint8Ar21ModulvezGFYPCJ7_p0V4XSymbLBNH6fTqQ35xD9ZREghasOw-cjkWK'
module.exports = function (size) { size = size || 21 var id = ''6 unmodified linesmodified:non-secure/index.js+1 added-1 removed
11234520 unmodified linesvar url = 'bjectSymhasOwnProp-0123456789ABCDEFGHIJKLMNQRTUVWXYZ_dfgiklquvxz'var url = 'sOwnPropMN49CEiq-hXvHJdSymlFURTag61GQfuD8YIWz2Zk5xKB7LV30_Abject'
/** * Generate URL-friendly unique ID. This method use non-secure predictable * random generator with bigger collision probability.20 unmodified linesadded:test/alphabet-genetic.js+112 added
1+let spawnSync = require('child_process').spawnSync2+let chalk = require('chalk')3+let path = require('path')4+let fs = require('fs')5+let geneticAlgorithmConstructor = require('geneticalgorithm')6+let gzipSize = require('gzip-size')7+8+if (!process.argv[2]) {9+ process.stderr.write(chalk.red('Pass a file with alphabet as argument\n'))10+ process.exit(1)11+}12+13+let input = path.join(process.cwd(), process.argv[2])14+let output = path.join(__dirname, '..', 'compiled.js')15+16+spawnSync('npx', ['webpack', '--mode', 'production', '--output', output, input])17+let js = fs.readFileSync(output).toString()18+fs.unlinkSync(output)19+20+let match = js.match(/[A-Za-z0-9-_]{30,}/)21+if (!match) {22+ process.stderr.write(chalk.red('Alphabet was not found\n'))23+ process.exit(1)24+}25+let alphabet = match[0]26+27+function mutationFunction (phenotype) {28+ let i = Math.floor(Math.random() * phenotype.alphabet.length)29+ let j = Math.floor(Math.random() * phenotype.alphabet.length)30+31+ return {32+ alphabet: swapChars(phenotype.alphabet, i, j)33+ }34+}35+36+function 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+}45+46+function 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)55+56+ return [57+ { alphabet: addMissingCharacter(newStrA, alphabetB) },58+ { alphabet: addMissingCharacter(newStrB, alphabetA) }59+ ]60+}61+62+function 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+}71+72+function 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+}78+79+function 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+}89+90+const firstPhenotype = { alphabet }91+92+const geneticAlgorithm = geneticAlgorithmConstructor({93+ mutationFunction,94+ crossoverFunction,95+ fitnessFunction,96+ population: [firstPhenotype],97+ populationSize: 500098+})99+100+console.log('Starting with:', firstPhenotype.alphabet)101+for (let i = 0; i < 100; i++) {102+ geneticAlgorithm.evolve()103+}104+const best = geneticAlgorithm.best()105+console.log('Finished with:', best.alphabet)106+const isSame = sameAlphabet(firstPhenotype.alphabet, best.alphabet)107+console.log('Same set of characters:',108+ isSame ? chalk.green('true') : chalk.red('false'))109+console.log(chalk.green('Size new string:',110+ gzipSize.sync(js.replace(/[A-Za-z0-9-_]{30,}/, best.alphabet))))111+console.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
18 unmodified lines192021222323242526276 unmodified lines18 unmodified lines/* * This alphabet uses a-z A-Z 0-9 _- symbols. * Symbols order was changed for better gzip compression. */var url = 'Uint8ArdomValuesObj012345679BCDEFGHIJKLMNPQRSTWXYZ_cfghkpqvwxyz-'var url = 'QLUint8ARdomValuesObj0h6345-79BCrypgJzHKTNYDSMkXPZ_FfG1WcqvwxEI2'
module.exports = function (size) { size = size || 21 var id = ''6 unmodified linesmodified:package.json+4 added-3 removed
48 unmodified lines49 "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 lines68 },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 linesmodified:url.js+1 added-1 removed
10 unmodified lines11121314151510 unmodified lines * const url = require('nanoid/url') * generate(url, 10) //=> "Uakgb_J5m9" */module.exports = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHIJKLNQRTUVWXYZ_cfgijkpqtvxz' 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'modified:yarn.lock+5 added
4382 unmodified lines4383 string-width "^1.0.1"4384 strip-ansi "^3.0.1"4385 wide-align "^1.1.0"4386 4387+geneticalgorithm@^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==4391+4392 get-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