Skip to content

Instantly share code, notes, and snippets.

@juntalis
Created May 11, 2013 16:49
Show Gist options
  • Select an option

  • Save juntalis/5560574 to your computer and use it in GitHub Desktop.

Select an option

Save juntalis/5560574 to your computer and use it in GitHub Desktop.
(function ($G, N, D, S, O, F, A, M, I, _undef) {
var undef, def,
J = 'JSON',
_S = 'tring',
SS = 'S'+_S,
c = 'call',
p = 'prototype',
sl = 'slice',
l = 'length',
t = 'to',
tJ = t+J,
tS = t+SS,
blank = '',
hOP = 'hasOwnProperty',
Z = '0000',
TE = TypeError,
tA = A[p][sl],
tAC = tA[c]
prims = ['s'+_S, 'object', 'number', 'boolean', 'undefined', 'date', 'regexp', 'function', 'array'],
typof = function(x) { var s, n = typeof(x); return n === prims[1] ? (s = O[p][tS][c](x)).substring(8, s[l] - 1).toLowerCase() : n; },
is = function(o, x) { var n = typof(o); return arguments[l] == 2 ? n === x : n; };
$G.is = (function(is, x) {
// Basics
is.nul = function(o) { return o == null || o == void 0; };
// Primitives
(function(is){
is.str = function(o) { return is(o, x[0]) };
is.obj = function(o) { return is(o, x[1]) };
is.num = function(o) { return is(o, x[2]) };
is.bool = function(o) { return is(o, x[3]) };
is.func = function(o) { return is(o, x[7]); };
undef = function(o) { return is(o, x[4]); };
def = function(o) { return !is(o, x[4]); };
})(is.prim = function(o, x, n) { n = typeof(o); return arguments[l] == 2 ? n === x : n; });
// Object instance-ish checks.
is.str = function(o) { return o instanceof S || is(o, x[0]); };
is.obj = function(o) { return o instanceof O || is(o, x[1]); };
is.num = function(o) { return o instanceof N || is(o, x[2]); };
is.arr = function(o) { return o instanceof A || is(o, x[8]); };
is.date = function(o) { return o instanceof D || is(o, x[5]); };
is.regex = function(o) { return o instanceof RegExp || is(o, x[6]); };
is.func = is.prim.func;
is.bool = is.prim.bool;
$G.undef = undef;
$G.def = def;
// Value checks
is.empty = function(o) { return undef(o) || is.nul(o) || undef(o[l]) || o[l] === 0; };
is.val = function(o) {
if(undef(o) || is.nul(o)) { return false; }
if(is.num(o)) { return o > 0; }
if(!is.empty(o) || is.obj(o) || (is.bool(o) && o)) { return true; }
return true;
};
return is;
})(is, prims);
(function(A, AA) {
var ensure = function (a, f) {
if (is.nul(a) || (arguments[l] === 2 && !is.func(f))) { throw new TE(); }
return O(a);
};
if (!A.every) {
A.every = function (fun, thisp) {
var x = ensure(this, fun),
len = x[l] >>> 0,
i = 0;
thisp = thisp || this;
for (; i < len; i++) {
if (i in x && !fun[c](thisp, x[i], i, x)) {
return false;
}
}
return true;
};
}
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/filter
if (!A.filter) {
A.filter = function (fun, thisp) {
var x = ensure(this, fun),
len = x[l] >>> 0,
res = [],
i = 0,
val;
thisp = thisp || this;
for (; i < len; i++) {
if (i in x) {
if (fun[c](thisp, val = x[i], i, x)) { res.push(val); }
}
}
return res;
};
}
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/array/foreach
if (!A.forEach) {
A.forEach = function (fun, thisp) {
var x = ensure(this, fun),
len = x[l] >>> 0,
i = 0;
thisp = thisp || this;
for (; i < len; i++) {
if (i in x) { fun[c](thisp, x[i], i, x); }
}
};
}
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/indexOf
if (!A.indexOf) {
A.indexOf = A.indexOf || function (searchElement, n) {
var x = ensure(this),
len = x[l] >>> 0;
n = n || 0;
if (len === 0) { return -1; }
if (arguments[l] > 1) {
if (n !== 0 && n !== (I) && n !== - (I)) {
n = (n > 0 || -1) * M.floor(M.abs(n));
}
}
if (n >= len) { return -1; }
var k = n >= 0
? n : M.max(len - M.abs(n), 0);
for (; k < len; k++) {
if (k in x && x[k] === searchElement) {
return k;
}
}
return -1;
};
}
A.contains = function(searchElement) { return this.indexOf(searchElement) !== -1; };
// Array.lastIndexOf(function, array)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/lastIndexOf
if (!A.lastIndexOf) {
A.lastIndexOf = function (searchElement, n) {
var x = ensure(this),
len = x[l] >>> 0;
n = n || 0;
if (len === 0) { return -1; }
if (arguments[l] > 1) {
if (n !== 0 && n !== (I) && n !== - (I)) {
n = (n > 0 || -1) * M.floor(M.abs(n));
}
}
var k = n >= 0 ? M.min(n, len - 1) : len - M.abs(n);
for (; k >= 0; k--) {
if (k in x && x[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Array.map(function, array)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/map
if (!A.map) {
A.map = function (fun, thisp) {
var x = ensure(this, fun),
len = x[l] >>> 0,
i = 0,
res = new AA(len);
thisp = thisp || this;
for (; i < len; i++) {
if (i in x) {
res[i] = fun[c](thisp, x[i], i, x);
}
}
return res;
};
}
// Array.reduce(function)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/Reduce
if (!A.reduce) {
A.reduce = function (fun) {
var x = ensure(this, fun),
len = x[l] >>> 0,
accumulator,
k = 0;
if (arguments[l] >= 2) {
accumulator = arguments[1];
} else {
do {
if (k in x) {
accumulator = x[k++];
break;
}
// if array contains no values, no initial value to return
if (++k >= len) {
throw new TE();
}
} while (true);
}
while (k < len) {
if (k in x) {
accumulator = fun[c](_undef, accumulator, x[k], k, x);
}
k++;
}
return accumulator;
};
}
// Array.reduceRight(function)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/ReduceRight
if (!A.reduceRight) {
A.reduceRight = function (fun) {
var x = ensure(this, fun),
len = x[l] >>> 0,
accumulator,
k = len - 1;
if (arguments[l] >= 2) {
accumulator = arguments[1];
} else {
do {
if (k in this) {
accumulator = this[k--];
break;
}
// if array contains no values, no initial value to return
if (--k < 0) {
throw new TE();
}
} while (true);
}
while (k >= 0) {
if (k in x) {
accumulator = fun[c](_undef, accumulator, x[k], k, x);
}
k--;
}
return accumulator;
};
}
// Array.some(function, array)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Array/some
if (!A.some) {
A.some = function (fun, thisp) {
var x = ensure(this, fun),
len = x[l] >>> 0,
i = 0;
thisp = thisp || this;
for (; i < len; i++) {
if (i in x && fun[c](thisp, x[i], i, x)) {
return true;
}
}
return false;
};
}
A.empty = function() { return this[l] === 0; };
})(A[p], A);
A.isArray = A.isArray || is.arr;
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Date/now
if (!D.now) {
D.now = function now() { return N(new D()); };
}
(function(D){
var X = t+'ISO'+SS;
if (!D[X]) {
D[X] = (function () {
var pad = function (n, length) {
length = length || 2;
return (n = n + blank, n[l] === length) ? n : pad("0" + n, length);
}
return function () {
var year = this.getUTCFullYear();
year = (year < 0 ? '-' : (year > 9999 ? '+' : blank)) + (Z+'0' + M.abs(year))[sl](0 <= year && year <= 9999 ? -4 : -6);
var date = [year, pad(this.getUTCMonth() + 1), pad(this.getUTCD())].join('-'),
time = [pad(this.getUTCHours()), pad(this.getUTCMinutes()), pad(this.getUTCSeconds())].join(':') + '.' + pad(this.getUTCMilliseconds(), 3);
return [date, time].join('T') + 'Z';
}
})();
}
D[tJ] = D[tJ] || D[X];
})(D[p]);
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Os/Function/bind
if (!F.bind) {
F.bind = function (obj) {
if (!is.func(this)) {
throw new TE('Function.'+p+'.bind - what is trying to be bound is not callable');
}
var args = tA(arguments, 1),
self = this,
nop = function () {},
bound = function () {
if (nop[p] && this instanceof nop) {
var result = self.apply(new nop, args.concat(tAC(arguments)));
return (O(result) === result) ? result : self;
} else {
return self.apply(obj, args.concat(tAC(arguments)));
};
};
nop[p] = self[p];
bound[p] = new nop();
return bound;
};
}
if (!O.getPrototypeOf) {
var ensure = function (o) {
if (o !== O(o)) { throw new TE('Object.getPrototypeOf called on non-object'); }
return o;
};
O.getPrototypeOf = is.prim.obj("test".__proto__) ?
function (o) { return ensure(o).__proto__; } : function (o) { return ensure(o).prototype; };
}
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
if (!O.keys) {
O.keys = (function () {
var hP = O[p][hOP],
hasDontEnumBug = !({
tS : null
}).propertyIsEnumerable(tS),
dontEnums = [
tS,
t+'Locale'+SS,
'valueOf',
hOP,
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums[l];
return function (obj) {
if (!is.prim.obj(obj) && !is.func(obj) || is.nul(obj)) {
throw new TE('Object.keys called on non-object');
}
var result = [], i = 0, prop;
for (prop in obj) {
if (hP[c](obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (; i < dontEnumsLength; i++) {
if (hP[c](obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
}
})()
}
O.typeOf = O.typeOf || typof;
(function(S){
if (!S.trim) {
S.trim = (function () {
var tl = /^\s\s*/,
tr = /\s\s*$/;
return function () {
return this.replace(tl, blank).replace(tr, blank);
};
})();
}
S.empty = A[p].empty;
S.contains = A[p].contains;
})(S[p]);
if (!$G[J]) {
(function(JSON, prims, _is, O, S) {
var gap, indent, rep,
cA = 'charCodeAt',
u = "\\u",
nul = 'null',
Q = '"',
ss = 'stringify',
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = { // table of character substitutions
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
Q : '\\"',
'\\' : '\\\\'
};
function q(string) {
escapable.lastIndex = 0;
return escapable.test(string) ? Q + string.replace(escapable, function (a) {
var x = meta[a];
return _is.str(x) ? x : u + (Z + a[cA](0)[tS](16))[sl](-4);
}) + Q : Q + string + Q;
}
function str(key, holder) {
var i, k, v, length, partial,
mind = gap,
value = holder[key],
typ = typof(value);
if (value && _is.obj(value) && _is.func(value[tJ])) {
value = value[tJ](key);
}
if (_is.func(rep)) {
value = rep[c](holder, key, value);
}
switch (typ) {
case prims[0]: return q(value);
case prims[2]: return isFinite(value) ? S(value) : nul;
case prims[3]:
case nul: return S(value);
case prims[1]:
if (!value) return nul;
gap += indent;
partial = [];
if (typ === prims[8]) {
length = value[l];
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || nul;
}
v = partial[l] === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
gap = mind;
return v;
}
if (rep && _is.obj(rep)) {
length = rep[l];
for (i = 0; i < length; i += 1) {
if (_is.str(rep[i])) {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(q(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
for (k in value) {
if (O[p][hOP][c](value, k)) {
v = str(k, value);
if (v) {
partial.push(q(k) + (gap ? ': ' : ':') + v);
}
}
}
}
v = partial[l] === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
if(!_is.func(JSON.stringify)) {
JSON.stringify = function (value, replacer, space) {
var i;
indent = gap = blank;
if (_is.num(space)) {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
} else if (_is.str(space)) {
indent = space;
}
rep = replacer;
if (replacer && _is.func(replacer) && (!_is.obj(replacer) || !_is.num(replacer[l]))) {
throw new Error(J+'.');
}
return str(blank, { blank : value });
};
}
if(!_is.func(JSON.parse)) {
JSON.parse = function (text, reviver) {
var j, walk = function(holder, key) {
var k, v, value = holder[key];
if (value && _is.obj(value)) {
for (k in value) {
if (O[p][hOP][c](value, k)) {
v = walk(value, k);
if (v !== _undef) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver[c](holder, key, value);
};
text = S(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) { return u + (Z + a[cA](0)[tS](16))[sl](-4); });
}
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, blank))) {
j = eval('(' + text + ')');
return _is.func(reviver) ? walk({ blank : j }, blank) : j;
}
throw new SyntaxError(J+'.parse');
};
}
})($G[J] = {}, prims, _is.prim, O, S);
}
})(window, Number, Date, String, Object, Function.prototype, Array, Math, Infinity);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment