Skip to content

Instantly share code, notes, and snippets.

@fabiospampinato
Created September 21, 2021 13:23
Show Gist options
  • Save fabiospampinato/a0091af6f87bcd98282e069f77613b86 to your computer and use it in GitHub Desktop.
Save fabiospampinato/a0091af6f87bcd98282e069f77613b86 to your computer and use it in GitHub Desktop.
Cursed base64 encoder.
// It's the fastest pure-JS base64 encoder (that doesn't account for padding though) that I've found.
// It's cursed because it takes ~2s to startup and 16MB of memory 😂
const encoder = new TextEncoder ();
const lookup = (() => {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split ( '' );
const lookup = new Array ( 2 ** 24 );
const mask1 = 0b11111100_00000000_00000000;
const mask2 = 0b00000011_11110000_00000000;
const mask3 = 0b00000000_00001111_11000000;
const mask4 = 0b00000000_00000000_00111111;
for ( let i = 0, l = lookup.length; i < l; i++ ) {
lookup[i] = alphabet[( i & mask1 ) >> 18] + alphabet[( i & mask2 ) >> 12] + alphabet[( i & mask3 ) >> 6] + alphabet[( i & mask4 )];
}
return lookup;
})();
const Base64 = {
encode: ( str: string ): string => {
const bytes = encoder.encode ( str );
let target = '';
for ( let i = 0, l = bytes.length; i < l; i += 3 ) {
target += lookup[( ( bytes[i] | 0 ) << 18 ) | ( ( bytes[i] | 1 ) << 12 ) | ( ( bytes[i] | 0 ) << 6 ) | ( bytes[i] | 0 )];
}
return target;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment