Created
May 5, 2014 18:28
-
-
Save derekr/a9d64b20fad8c13d00f5 to your computer and use it in GitHub Desktop.
Browser shim for util to only include what we use
This file contains 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
/** | |
* DIY browser shim for node's `util` | |
* | |
* @package www | |
* @author Derek Reynolds <drk@diy.org> | |
*/ | |
// NOTE: These type checking functions intentionally don't use `instanceof` | |
// because it is fragile and can be easily faked with `Object.create()`. | |
function isArray (ar) { | |
if (typeof Array.isArray === 'function') return Array.isArray(ar); | |
return Object.prototype.toString.call(ar) === '[object Array]'; | |
} | |
function isBoolean (arg) { | |
return typeof arg === 'boolean'; | |
} | |
function isFunction (arg) { | |
return typeof arg === 'function'; | |
} | |
function isObject (arg) { | |
return typeof arg === 'object' && arg; | |
} | |
function isNull (arg) { | |
return arg === null; | |
} | |
function isNumber (arg) { | |
return typeof arg === 'number'; | |
} | |
function isString (arg) { | |
return typeof arg === 'string'; | |
} | |
function isUndefined (arg) { | |
return arg === void 0; | |
} | |
/** | |
* util.format browser shim | |
* | |
* First param is string to format and any other arguments will | |
* be used as replacements within the format string. | |
* | |
* @param {string} f - String to format | |
*/ | |
function format (f) { | |
var i; | |
if (!isString(f)) { | |
return; // noop | |
} | |
i = 1; | |
var args = arguments; | |
var len = args.length; | |
var str = String(f).replace(/%[sdj%]/g, function(x) { | |
if (x === '%%') return '%'; | |
if (i >= len) return x; | |
switch (x) { | |
case '%s': return String(args[i++]); | |
case '%d': return Number(args[i++]); | |
case '%j': | |
try { | |
return JSON.stringify(args[i++]); | |
} catch (_) { | |
return '[Circular]'; | |
} | |
break; | |
default: | |
return x; | |
} | |
}); | |
for (var x = args[i]; i < len; x = args[++i]) { | |
if (isNull(x) || !isObject(x)) { | |
str += ' ' + x; | |
} else { | |
str += ' '; // noop | |
} | |
} | |
return str; | |
} | |
/** | |
* Exports | |
*/ | |
module.exports = { | |
format: format, | |
inherits: require('inherits'), | |
isBoolean: isBoolean, | |
isArray: isArray, | |
isFunction: isFunction, | |
isObject: isObject, | |
isNull: isNull, | |
isNumber: isNumber, | |
isString: isString, | |
isUndefined: isUndefined | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment