Last active
June 18, 2018 13:13
-
-
Save e-mihaylin/e60cbbf3f1bd69ced7b419ae33973cfe to your computer and use it in GitHub Desktop.
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
//Extend the String object with toBase64() and fromBase64() functions | |
String.prototype.toBase64 = function () { | |
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; | |
let result = ''; | |
let i = 0; | |
while (i < this.length) { | |
let a = this.charCodeAt(i++) || 0; | |
let b = this.charCodeAt(i++) || 0; | |
let c = this.charCodeAt(i++) || 0; | |
let b1 = (a >> 2) & 0x3F; | |
let b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF); | |
let b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3); | |
let b4 = c & 0x3F; | |
if (!b) b3 = b4 = 64; | |
else if (!c) b4 = 64; | |
result += characters.charAt(b1) + | |
characters.charAt(b2) + | |
characters.charAt(b3) + | |
characters.charAt(b4); | |
} | |
return result; | |
} | |
String.prototype.fromBase64 = function () { | |
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; | |
let result = ''; | |
let i = 0; | |
while (i < this.length) { | |
var b1 = characters.indexOf(this.charAt(i++)); | |
var b2 = characters.indexOf(this.charAt(i++)); | |
var b3 = characters.indexOf(this.charAt(i++)); | |
var b4 = characters.indexOf(this.charAt(i++)); | |
var a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3); | |
var b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF); | |
var c = ((b3 & 0x3) << 6) | (b4 & 0x3F); | |
result += String.fromCharCode(a) + | |
(b ? String.fromCharCode(b) : '') + | |
(c ? String.fromCharCode(c) : ''); | |
}; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment