Skip to content

Instantly share code, notes, and snippets.

@BorisChumichev
Forked from derekr/util.js
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BorisChumichev/98d3717c2e701e52f2d3 to your computer and use it in GitHub Desktop.
Save BorisChumichev/98d3717c2e701e52f2d3 to your computer and use it in GitHub Desktop.
/**
* 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