get-display-type.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var TYPES = require('./helpers/types');
  6. /**
  7. * Given a value, return an INFORMAL type string loosely
  8. * representing its data type.
  9. *
  10. * WARNING: THIS FUNCTION IS NOT ALL THAT IT SEEMS.
  11. * It does not return an RDT ("RTTC display type")-- it returns a display string
  12. * that might include other values as well, such as `'undefined'`, `'null',
  13. * `'Date'`, etc.
  14. *
  15. * > ------------------------------------------------------------------------
  16. * > NOTE:
  17. * > THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED IN FAVOR OF MORE
  18. * > SPECIFIC UTILITY METHODS IN AN UPCOMING RELEASE OF RTTC.
  19. * > ------------------------------------------------------------------------
  20. *
  21. * TODO: Remove this
  22. *
  23. * @param {===} val
  24. * @return {String}
  25. */
  26. module.exports = function getDisplayType(val){
  27. // `undefined` should take precedence over special exemplar syntax
  28. // (i.e. '===')
  29. if (_.isUndefined(val)) return 'undefined';
  30. if (TYPES.json.isExemplar(val)) return 'json';
  31. if (TYPES.lamda.isExemplar(val)) return 'lamda';
  32. if (TYPES.ref.isExemplar(val)) return 'ref';
  33. if (_.isEqual(val, Infinity) || _.isEqual(val, -Infinity) || _.isNaN(val)) {
  34. return 'invalid number';
  35. }
  36. if (_.isString(val)) return 'string';
  37. if (_.isNumber(val)) return 'number';
  38. if (_.isBoolean(val)) return 'boolean';
  39. if (_.isNull(val)) return 'null';
  40. if (_.isArray(val)) return 'array';
  41. if (_.isFunction(val)) return 'function';
  42. if (_.isDate(val)) return 'Date';
  43. if (_.isError(val)) return 'Error';
  44. if (_.isRegExp(val)) return 'RegExp';
  45. // If it's an object
  46. if (_.isObject(val)) {
  47. var displayType = typeof val;
  48. try {
  49. displayType = val.constructor.name;
  50. if (displayType.match(/object/i) && _.isPlainObject(val)) {
  51. return 'dictionary';
  52. }
  53. // Use the constructor name if it's anything other than "Object"
  54. return displayType;
  55. }
  56. catch (e){}
  57. }
  58. // ok.. wtf is it?
  59. return 'unknown';
  60. };