Created
August 25, 2014 22:21
-
-
Save yitsushi/e75ee2f8ede72ba2c837 to your computer and use it in GitHub Desktop.
Only for ASCII text and does not contain validation. Inspired on Base64 Encoding Kata (thanks joseph.varnado to the kata)
This file contains hidden or 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
var Int6 = (function() { | |
// Base64 ABC contains only A-Z, a-z, 0-9, + and / | |
// (and the = sign but it's just a marker) | |
var ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
return { | |
toChar: function(e) { return ABC.substr(e, 1); }, | |
fromChar: function(e) { return ABC.indexOf(e); } | |
}; | |
}()); | |
String.prototype.toBase64 = function() { | |
// Split the string into characters | |
// Convert each characer into a 8 bit binary number string | |
// Join binary numbers | |
var binary = this.split("").map(function(char) { | |
var binary = char.charCodeAt().toString(2); | |
return (new Array(9 - binary.length)).join(0) + binary; | |
}).join(""); | |
// Calulcate how many extra bits are needed | |
// and save the marker count | |
var postfix = new Array(binary.length % 3 + 1).join('='); | |
// Left padding zeros to fill the missing bits | |
binary += new Array(binary.length % 3 * 2 + 1).join(0); | |
// Split the final binary into 6 bits length strings | |
// Get the 6 bit value (from Base64 ABC) | |
// Join them and add the postfix (line 22) | |
// Postfix sould be: "" (nothing), "=" and "==" | |
return binary.match(/.{1,6}/g) | |
.map(function(char) { | |
return Int6.toChar(parseInt(char, 2)); | |
}) | |
.join("") + postfix; | |
}; | |
String.prototype.fromBase64 = function() { | |
// Get the number of = signs at the end | |
// Multiply by 2 to get the padding 0 bits | |
var fixBits = (this.match(/=+$/g) || [""])[0].length * 2; | |
// Remove the = signs | |
// Split into characters | |
// Get the Base64 ABC based index and convert into binary | |
// Add the missing right padding zeros | |
var binary = this.replace(/=+$/, "").split("").map(function(char) { | |
var binary = Int6.fromChar(char).toString(2); | |
return (new Array(7 - binary.length)).join(0) + binary; | |
}).join(""); | |
// Remove left padding zeros based on line 40 | |
binary = binary.substr(0, binary.length - fixBits); | |
// Split the final binary string into 8 bits length strings | |
// Get the ASCII code of the given binary number | |
// Join them to the final string | |
return binary.match(/.{1,8}/g) | |
.map(function(char) { | |
return String.fromCharCode(parseInt(char, 2)); | |
}) | |
.join(""); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment