From 1e474350588046ed0378c068e1cfeb083e09db4a Mon Sep 17 00:00:00 2001 From: rolux Date: Fri, 15 Jun 2012 10:39:22 +0200 Subject: [PATCH] add atob and btoa polyfills --- source/Ox/js/Polyfill.js | 44 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/source/Ox/js/Polyfill.js b/source/Ox/js/Polyfill.js index 65a3fbbb..2f01105a 100644 --- a/source/Ox/js/Polyfill.js +++ b/source/Ox/js/Polyfill.js @@ -2,6 +2,47 @@ Ox.polyfill = {}; +(function() { + var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + /*@ + Ox.polyfill.atob see https://developer.mozilla.org/en/DOM/window.atob + > Ox.polyfill.atob('Cg==') + '\n' + > Ox.polyfill.atob('Zm9v') + 'foo' + @*/ + Ox.polyfill.atob = function(string) { + var binary = '', ret = ''; + String(string).replace(/=/g, '').split('').forEach(function(char) { + binary += Ox.pad(digits.indexOf(char).toString(2), 'left', 6, '0'); + }); + while (binary.length >= 8) { + ret += Ox.char(parseInt(binary.slice(0, 8), 2)); + binary = binary.slice(8); + } + return ret; + }; + /*@ + Ox.polyfill.btoa see https://developer.mozilla.org/en/DOM/window.btoa + > Ox.polyfill.btoa('\n') + 'Cg==' + > Ox.polyfill.btoa('foo') + 'Zm9v' + @*/ + Ox.polyfill.btoa = function(string) { + var binary = '', ret = ''; + String(string).split('').forEach(function(char) { + binary += Ox.pad(char.charCodeAt(0).toString(2), 'left', 8, '0'); + }); + binary = Ox.pad(binary, Math.ceil(binary.length / 6) * 6, '0') + while (binary) { + ret += digits[parseInt(binary.slice(0, 6), 2)]; + binary = binary.slice(6); + } + return Ox.pad(ret, Math.ceil(ret.length / 4) * 4, '='); + }; +}()); + (function(window) { /*@ Ox.polyfill.bind see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind @@ -343,7 +384,8 @@ Ox.polyfill.trim = function() { for (key in Ox.polyfill) { object = key == 'bind' ? Function.prototype : key == 'isArray' ? Array - : key == 'JSON' || key == 'localStorage' ? window + : key == 'atob' || key == 'btoa' + || key == 'JSON' || key == 'localStorage' ? window : key == 'keys' ? Object : key == 'trim' ? String.prototype : Array.prototype;