Skip to content

Instantly share code, notes, and snippets.

@Little-Ki
Last active September 19, 2023 02:43
Show Gist options
  • Save Little-Ki/627213bf5ff43c37f48be04a44a3203e to your computer and use it in GitHub Desktop.
Save Little-Ki/627213bf5ff43c37f48be04a44a3203e to your computer and use it in GitHub Desktop.
[TypeScript] Base64
let Base64 = (function () {
let dic = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let encode = (array: Int8Array | Uint8Array | number[]) => {
let result = [];
let i = 0;
while (i < array.length) {
let b0 = array[i++];
let b1 = array[i++];
let b2 = array[i++];
let en = ((b0 & 0xff) << 16) | ((b1 & 0xff) << 8) | (b2 & 0xff);
let e0 = (en >> 18) & 0x3f;
let e1 = (en >> 12) & 0x3f;
let e2 = (en >> 6) & 0x3f;
let e3 = en & 0x3f;
if (b1 === undefined) e2 = 64;
if (b2 === undefined) e3 = 64;
result.push(dic.charAt(e0));
result.push(dic.charAt(e1));
result.push(dic.charAt(e2));
result.push(dic.charAt(e3));
}
return result.join("");
};
let decode = (string: String) => {
let array = [];
let i = 0;
string = string.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < string.length) {
let e0 = dic.indexOf(string.charAt(i++));
let e1 = dic.indexOf(string.charAt(i++));
let e2 = dic.indexOf(string.charAt(i++));
let e3 = dic.indexOf(string.charAt(i++));
let en = (e0 << 18) | (e1 << 12) | (e2 << 6) | e3;
let b0 = (en >> 16) & 0xff;
let b1 = (en >> 8) & 0xff;
let b2 = en & 0xff;
array.push(b0);
if (e2 !== 64) array.push(b1);
if (e3 !== 64) array.push(b2);
}
return array;
};
let encodeString = (string: String) => {
return encode([...string].map((it) => it.charCodeAt(0)));
};
let decodeString = (string: String) => {
return String.fromCharCode(...decode(string));
};
return { encode, decode, encodeString, decodeString };
})();
export default Base64;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment