From 3138600caf40c6f6c0df56d9b34de80fddd2918a Mon Sep 17 00:00:00 2001 From: Idan Gazit Date: Thu, 10 Dec 2015 17:19:26 +0200 Subject: [PATCH] Adding btoa polyfill --- lib/helpers/btoa.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 lib/helpers/btoa.js diff --git a/lib/helpers/btoa.js b/lib/helpers/btoa.js new file mode 100644 index 0000000..86f45b7 --- /dev/null +++ b/lib/helpers/btoa.js @@ -0,0 +1,34 @@ +'use strict'; + +// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function InvalidCharacterError(message) { + this.message = message; +} +InvalidCharacterError.prototype = new Error; +InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + +function btoa (input) { + var str = String(input); + for ( + // initialize result and counter + var block, charCode, idx = 0, map = chars, output = ''; + // if the next str index does not exist: + // change the mapping table to "=" + // check if d has no fractional digits + str.charAt(idx | 0) || (map = '=', idx % 1); + // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 + output += map.charAt(63 & block >> 8 - idx % 1 * 8) + ) { + charCode = str.charCodeAt(idx += 3/4); + if (charCode > 0xFF) { + throw new InvalidCharacterError('\'btoa\' failed: The string to be encoded contains characters outside of the Latin1 range.'); + } + block = block << 8 | charCode; + } + return output; +}; + +module.exports = btoa -- GitLab