Last active
December 17, 2017 19:46
-
-
Save btk5h/a1ceffa530818a168536195df1d00ba7 to your computer and use it in GitHub Desktop.
Compactly represent an array of integers as a string using the base64 alphabet. 40% to 50% smaller output than JSON.stringify.
This file contains 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
const TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('') | |
function encodeInt (int) { | |
let encoded = '' | |
do { | |
let offset = int & 0b011111 | |
int >>>= 5 | |
if (int === 0) { | |
offset |= 0b100000 | |
} | |
encoded += TABLE[offset] | |
} while (int !== 0) | |
return encoded | |
} | |
export function decodeIntArray (ser) { | |
const arr = [] | |
const stringLength = ser.length | |
let currentInt = 0 | |
let currentShift = 0 | |
for (let i = 0; i < stringLength; i++) { | |
const char = ser.charAt(i) | |
const offset = TABLE.indexOf(char) | |
const numPart = offset & 0b011111 | |
const isEnd = !!(offset & 0b100000) | |
currentInt |= (numPart << currentShift) | |
currentShift += 5 | |
if (isEnd) { | |
arr.push(currentInt) | |
currentInt = 0 | |
currentShift = 0 | |
} | |
} | |
return arr | |
} | |
export function encodeIntArray (arr) { | |
return arr.map(encodeInt).join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment