infer-display-type.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Module dependencies
  3. */
  4. var types = require('./helpers/types');
  5. var inferPrimitive = require('./helpers/infer-primitive');
  6. /**
  7. * Given an RTTC exemplar, compute the display type string (aka "typeclass").
  8. *
  9. * For example, given `{foo: 'bar'}`, this returns `'dictionary'`,
  10. * and given `'->'`, this returns `'ref'`. And so forth.
  11. *
  12. *
  13. * @param {JSON} exemplar
  14. * e.g. `{soup: 'Rabbit soup'}`
  15. *
  16. * @returns {String} [display type]
  17. * Returns one of the standard RTTC display types:
  18. * • string
  19. * • number
  20. * • boolean
  21. * • lamda
  22. * • dictionary
  23. * • array
  24. * • json
  25. * • ref
  26. * ...or '' (empty string is the catchall if exemplar is unrecognized; e.g. `null`)
  27. */
  28. module.exports = function inferDisplayType(exemplar){
  29. // Currently `types.ref.is(undefined)` returns true. This will change in
  30. // future of RTTC, but to preserve compatibility, we are leaving it the way
  31. // it is for the time being. So we check that the exemplar is not `undefined`
  32. // out here. (We should pull this into the `isExemplar` function of the `ref` type
  33. // in a future major version release).
  34. if (typeof exemplar === 'undefined') {
  35. return '';
  36. }
  37. // If the exemplar isn't a dictionary or array, we will infer
  38. // its type without messing around with any kind of recursion.
  39. if(!types.dictionary.is(exemplar) && !types.array.is(exemplar)) {
  40. var displayType = inferPrimitive(exemplar);
  41. // If inferPrimitive returned something other than undefined, everything is in order.
  42. if (typeof displayType !== 'undefined') {
  43. return displayType;
  44. }
  45. // But otherwise, this exemplar must be null or undefined-- or perhaps something
  46. // completely strange, so we return empty string to indicate voidness and/or
  47. // our confusion.
  48. else {
  49. return '';
  50. }
  51. }
  52. // Otherwise, if the exemplar is an array, we return 'array'.
  53. else if(types.array.is(exemplar)) {
  54. return 'array';
  55. }
  56. // Otherwise, if the exemplar is a dictionary, we return 'dictionary'.
  57. else if(types.dictionary.is(exemplar)){
  58. return 'dictionary';
  59. }
  60. else {
  61. throw new Error('Consistency violation: Unexpected logic error in RTTC.');
  62. }
  63. };