Skip to content

Instantly share code, notes, and snippets.

@vermie
Created July 2, 2015 22:12
Show Gist options
  • Save vermie/a59a05543c33d1b03595 to your computer and use it in GitHub Desktop.
Save vermie/a59a05543c33d1b03595 to your computer and use it in GitHub Desktop.
var bacon = (function () {
var bacon = {},
defaultBase = 2;
function getEncodedWidth(alphabet, base) {
var width = 1 + Math.floor(Math.log(alphabet.length) / Math.log(base));
return width;
}
function padLeft(str, char, length) {
var padLength = Math.max(length - str.length);
var pad = Math.pow(10, padLength).toString().substr(-padLength).replace('0', char);
return pad + str;
}
function getMap(alphabet, base) {
var baseMap = bacon[base];
if (!baseMap) {
bacon[base] = baseMap = {};
}
var alphaMap = baseMap[alphabet];
if (!alphaMap) {
var width = getEncodedWidth(alphabet, base);
baseMap[alphabet] = alphaMap = [].reduce.call(alphabet, function (m, c, i) {
var value = i.toString(base);
value = padLeft(value, '0', width);
m.encodings[c] = value;
m.decodings[value] = c;
return m;
}, { encodings: {}, decodings: {} });
}
return alphaMap;
}
function encode(value, alphabet, base) {
base = Math.abs(base) || defaultBase;
var map = getMap(alphabet, base);
var encodings = [].map.call(value, function (c) {
return map.encodings[c];
});
return encodings.join('');
}
function decode(value, alphabet, base) {
base = Math.abs(base) || defaultBase;
var width = getEncodedWidth(alphabet, base);
var map = getMap(alphabet, base);
var characters = value.match(new RegExp('.{' + width + '}', 'g'));
var decodings = characters.map(function (c) {
return map.decodings[c];
});
return decodings.join('');
}
return {
encode: encode,
decode: decode
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment