Skip to content

Instantly share code, notes, and snippets.

@rubeniskov
Created April 28, 2016 08:05
Show Gist options
  • Save rubeniskov/0891d4b35f013871914e955faf058fd9 to your computer and use it in GitHub Desktop.
Save rubeniskov/0891d4b35f013871914e955faf058fd9 to your computer and use it in GitHub Desktop.
base64 compression ObjectID
var base64 = (function(bin) {
for (var i = 0, l = bin.chars.length; i < l; i++)
bin.tabs[bin.chars.charAt(i)] = i;
return bin;
})({
chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+_',
tabs: {}
}),
encode = function(objectID) {
var oid = objectID.toUpperCase(),
bas = '';
for (var pos = 0, chunk; pos < oid.length;) {
chunk = base64.tabs[oid[pos++]] << 8 | base64.tabs[oid[pos++]] << 4 | base64.tabs[oid[pos++]];
bas += base64.chars[chunk >>> 6 & 63] + base64.chars[chunk & 63];
}
return bas;
},
decode = function(encoded) {
var hex = '';
for (var pos = 0, chunk; pos < encoded.length;) {
chunk = base64.tabs[encoded[pos++]] << 6 | base64.tabs[encoded[pos++]];
hex += base64.chars[chunk >>> 8 & 15] + base64.chars[chunk >>> 4 & 15] + base64.chars[chunk & 15];
}
return hex.toLowerCase();
}
var code = '6089cc0da',
ecode = encode(code),
dcode = decode(ecode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment