Created
November 20, 2014 19:40
-
-
Save geraintluff/367c65ea13d83454364f to your computer and use it in GitHub Desktop.
JavaScript Crusher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2014 Geraint Luff | |
// MIT Licensed | |
function crush(code, searchLimit) { | |
var originalCode = code; | |
searchLimit = searchLimit || 15; | |
var substitutions = []; | |
var bannedChars = /[\r\n"'\\]/; | |
for (var charNum = 32; charNum < 127; charNum++) { // ASCII printable ("safe") characters | |
var char = String.fromCharCode(charNum); | |
if (code.indexOf(char) !== -1 || bannedChars.test(char)) continue; | |
// Find best replacement | |
var sequences = {}; | |
for (var i = 0; i < code.length; i++) { | |
for (var j = 2; i + j < code.length && j < searchLimit; j++) { | |
var extract = code.substring(i, i + j); | |
sequences[extract] = (sequences[extract] || 0) + 1; | |
} | |
} | |
var bestScore = 0, bestSub = null; | |
for (var extract in sequences) { | |
var score = (JSON.stringify(extract).length - 2)*(sequences[extract] - 1) - 1; | |
if (score > bestScore) { | |
bestScore = score; | |
bestSub = extract; | |
} | |
} | |
if (bestSub) { | |
substitutions.push([char, bestSub]); | |
code = code.split(bestSub).concat(bestSub).join(char); | |
} | |
} | |
var stringConstant = '"' + code.replace(/\\/g, '\\\\').replace(/"/g, "\\\"") + '"'; | |
var stringConstantAlt = "'" + code.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"; | |
if (stringConstantAlt.length < stringConstant.length) stringConstant = stringConstantAlt; | |
var subChars = substitutions.map(function (pair) { | |
return pair[0]; | |
}).join(''); | |
var newCode = 'c=' + stringConstant + ';'; | |
newCode += 'for(i=' + subChars.length + ';i--;)'; | |
newCode += 'c=c.split("' + subChars + '"[i]),c=c.join(c.pop());'; | |
newCode += 'eval(c);'; | |
return newCode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Currently not quite as good as
jscrush
(or other projects based on a similar code-base), but I couldn't find any license information for that project, so I wrote my own.