Refactor Polyfill.js, use Object.defineProperty if available

This commit is contained in:
rolux 2013-12-04 09:47:35 +01:00
parent 828e814812
commit 4471a8657f

View file

@ -1,9 +1,18 @@
'use strict';
(function(window) {
var canDefineProperty = !!Object.defineProperty && (function() {
try {
Object.defineProperty({}, 'a', {});
return true;
} catch (e) {} // IE 8
}()),
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
log;
Ox.polyfill = {};
(function() {
var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
/*@
Ox.polyfill.atob <f> see https://developer.mozilla.org/en/DOM/window.atob
> Ox.polyfill.atob('Cg==')
@ -14,7 +23,7 @@ Ox.polyfill = {};
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');
binary += Ox.pad(chars.indexOf(char).toString(2), 'left', 6, '0');
});
while (binary.length >= 8) {
ret += Ox.char(parseInt(binary.slice(0, 8), 2));
@ -36,14 +45,12 @@ Ox.polyfill = {};
});
binary = Ox.pad(binary, Math.ceil(binary.length / 6) * 6, '0')
while (binary) {
ret += digits[parseInt(binary.slice(0, 6), 2)];
ret += chars[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 <f> see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
<script>
@ -80,7 +87,6 @@ Ox.polyfill = {};
ret.prototype = new fn();
return ret;
};
})(this);
/*@
Ox.polyfill.every <f> see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
@ -377,19 +383,34 @@ Ox.polyfill.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
(function(window) {
var key, log, object;
for (key in Ox.polyfill) {
object = key == 'bind' ? Function.prototype
: key == 'isArray' ? Array
: key == 'atob' || key == 'btoa' || key == 'JSON' ? window
: key == 'keys' ? Object
: key == 'trim' ? String.prototype
: Array.prototype;
if (!object[key]) {
[
[Array, ['isArray']],
[Array.prototype, [
'every', 'filter', 'forEach', 'indexOf', 'lastIndexOf',
'map', 'reduce', 'reduceRight', 'some']
],
[Function.prototype, ['bind']],
[Object, ['keys']],
[String.prototype, ['trim']],
[window, ['atob', 'btoa', 'JSON']]
].forEach(function(item) {
var object = item[0], keys = item[1];
keys.forEach(function(key) {
if (!key in object) {
if (canDefineProperty) {
Object.defineProperty(object, key, {
configurable: true,
enumerable: false,
writable: true,
value: Ox.polyfill[key]
});
} else {
object[key] = Ox.polyfill[key];
}
}
});
});
// In IE8, window.console.log is an object,
// in IE9, window.console.log.apply is undefined
// see http://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function
@ -405,4 +426,5 @@ Ox.polyfill.trim = function() {
);
}
}
})(this);