all files / lib/offshore/utils/ helpers.js

79.17% Statements 19/24
70.59% Branches 12/17
83.33% Functions 5/6
85.71% Lines 18/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                          15× 15× 15×                                                       20936× 20936×                                 409268× 409262×                           2355×   46× 2309×    
 
/**
 * Module Dependencies
 */
 
var _ = require('lodash');
 
/**
 * Equivalent to _.objMap, _.map for objects, keeps key/value associations
 *
 * Should be deprecated.
 *
 * @api public
 */
exports.objMap = function objMap(input, mapper, context) {
  return _.reduce(input, function(obj, v, k) {
    obj[k] = mapper.call(context, v, k, input);
    return obj;
  }, {}, context);
};
 
/**
 * Run a method meant for a single object on a object OR array
 * For an object, run the method and return the result.
 * For a list, run the method on each item return the resulting array.
 * For anything else, return it silently.
 *
 * Should be deprecated.
 *
 * @api public
 */
 
exports.pluralize = function pluralize(collection, application) {
  if (Array.isArray(collection)) return _.map(collection, application);
  if (_.isObject(collection)) return application(collection);
  return collection;
};
 
/**
 * _.str.capitalize
 *
 * @param {String} str
 * @return {String}
 * @api public
 */
 
exports.capitalize = function capitalize(str) {
  str = str === null ? '' : String(str);
  return str.charAt(0).toUpperCase() + str.slice(1);
};
 
/**
 * ignore
 */
 
exports.object = {};
 
/**
 * Safer helper for hasOwnProperty checks
 *
 * @param {Object} obj
 * @param {String} prop
 * @return {Boolean}
 * @api public
 */
 
var hop = Object.prototype.hasOwnProperty;
exports.object.hasOwnProperty = function(obj, prop) {
  if (obj === null || obj === undefined) return false;
  return hop.call(obj, prop);
};
 
/**
 * Check if an ID resembles a Mongo BSON ID.
 * Can't use the `hop` helper above because BSON ID's will have their own hasOwnProperty value.
 *
 * @param {String} id
 * @return {Boolean}
 * @api public
 */
 
exports.matchMongoId = function matchMongoId(id) {
  // id must be truthy- and either BE a string, or be an object
  // with a toString method.
  if (!id ||
   !(_.isString(id) || (_.isObject(id) || _.isFunction(id.toString)))
  ) return false;
  else return /^[a-fA-F0-9]{24}$/.test(id.toString());
};