Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hraban/be955b8044dd4871e3f5 to your computer and use it in GitHub Desktop.
Save hraban/be955b8044dd4871e3f5 to your computer and use it in GitHub Desktop.
encode array of strings literal in js by length
// Copyright © 2014 Hraban Luyat <hraban@0brg.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// alternative way to encode a large literal array of strings to save some space
// at the cost of decoding speed.
//
// generalization of this problem: how to order the elements in a set literal
// for optimal compression by a compression algorithm that preserves order (gzip
// &c)?
var adjectives = "tan shy wee odd next hard both oval blue twin same lazy late trim half vast sour free poor cool bony this each rash ugly tidy limp ideal front glass clear baggy silly close fresh loyal testy prime nasty hairy rusty bleak pesky jumpy lanky minty soggy windy mealy swift gross sunny flaky witty juicy blond tough weepy mixed quick scary dizzy noisy rowdy perky adept nifty super mushy petty phony grand brave vapid remote pretty unique hidden actual thorny daring cheery frigid flimsy edible robust arctic better oblong severe golden watery single intent bright frozen dreary snappy wiggly klutzy pastel flashy ringed fickle glossy tinted knotty medium female tragic jaunty square ornate sugary subtle grouchy buoyant growing worried darling unhappy pungent perfect ashamed limited harmful pleased profuse weighty striped distant vibrant focused monthly similar regular devoted classic worldly failing delayed yawning stylish assured massive teeming crowded spotted melodic average distant faraway knowing corrupt required indolent scratchy wrathful vigilant sizzling haunting enormous tangible terrible polished grizzled flawless informal forsaken discrete lustrous nautical frequent infinite educated favorite motherly inferior metallic circular rotating gorgeous physical expensive delirious different foolhardy alienated acclaimed anguished worthless sorrowful unnatural talkative overjoyed exemplary conscious quarterly ill-fated palatable memorable well-made worrisome evergreen indelible authentic imperfect humongous impeccable impressive elliptical impossible beneficial celebrated improbable sweltering courageous supportive disastrous gregarious remorseful equatorial glittering cumbersome short-term bite-sized extraneous adolescent profitable unimportant frightening astonishing interesting extra-small kindhearted neighboring everlasting trustworthy complicated warmhearted outstanding quarrelsome appropriate incompatible quick-witted compassionate biodegradable international uncomfortable inconsequential";
// analogous to Python's itertools.groupby. key is called exactly once for each
// element.
function groupby(ar, key) {
var result = {};
for (var i = 0; i < ar.length ; i++) {
var el = ar[i];
var k = key(el);
var group = result[k];
if (group === undefined) {
group = [];
result[k] = group;
}
group.push(el);
}
return result;
}
function indexedArray(obj) {
var result = [];
for (var key in obj) {
result.push([key, obj[key]]);
}
return result;
}
function strlen(x) {
return x.length;
}
function length_compressor(ar, splitchar) {
if (splitchar === undefined) {
throw "split character marker required";
}
var groups = groupby(ar, strlen);
groups = indexedArray(groups);
groups = groups.map(function (group) {
return [+group[0], group[1]];
});
groups = groups.sort(function (a, b) {
return a[0] - b[0];
});
var result = [];
var oldlen = 0;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var len = group[0];
var words = group[1];
var d = len - oldlen;
// gaps > 9 mess with the decompressor
while (d > 9) {
result.push(splitchar + '9');
d -= 9;
}
result.push(splitchar + d);
result.push.apply(result, words);
oldlen = len;
}
return result.join('');
}
function decompress_raw(lit) {
var splitchar = lit[0],
split = lit.slice(1).split(splitchar),
result = [],
len = 0;
split.forEach(function (x) {
// requires 0 <= jump <= 9
len += +x[0];
for (var i = 1; i < x.length; i += len) {
result.push(x.slice(i, i+len));
}
})
return result;
}
// minified version for char count (includes function name)
function decompress(d){var e=[],b=0;d.slice(1).split(d[0]).forEach(function(c){b+=+c[0];for(var a=1;a<c.length;a+=b)e.push(c.slice(a,a+b))});return e}
var adjectives_list = adjectives.split(' ');
// a determine_splitchar() function a la jscrush would be nice
var compressed = length_compressor(adjectives_list, '.');
console.log('compressed literal length: '+compressed.length);
console.log('old literal length: '+adjectives.length);
var decompressfunclen = decompress.toString().length;
console.log('length of minified compression function: ' + decompressfunclen
+ ' bytes');
var splitfunclen = '.split(" ")'.length;
var oldlen = adjectives.length + splitfunclen;
var newlen = compressed.length + decompressfunclen;
console.log('savings: ' + (oldlen - newlen) + ' bytes');
// test
var decomp = decompress(compressed);
console.log('decompress(compress(x)) === x (should be true!): ' + (adjectives === decomp.join(' ')));
// Output:
// compressed literal length: 1794
// old literal length: 2019
// length of minified compression function: 150 bytes
// savings: 86 bytes
// decompress(compress(x)) === x (should be true!): true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment