build-schema-iterator.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. /**
  6. * Build an iterator/reducer function for a schema that builds up and returns a new value.
  7. *
  8. * Note that this works for either type schemas OR exemplars!
  9. *
  10. * @param {Function} onFacetDict
  11. * -> @param {Object} facetDictionary
  12. * -> @param {String} parentKeyOrIndex
  13. * -> @param {Function} iterateRecursive(nextSchema, nextKey)
  14. * -> @returns {*} value for this part of our result
  15. *
  16. * @param {Function} onPatternArray
  17. * -> @param {Array} patternArray
  18. * -> @param {String} parentKeyOrIndex
  19. * -> @param {Function} iterateRecursive(nextSchema, nextIndex)
  20. * -> @returns {*} value for this part of our result
  21. *
  22. * @param {Function} onGenericDict
  23. * -> @param {Object} schema -- (this is always `{}`)
  24. * -> @param {String} parentKeyOrIndex
  25. * -> @returns {*} value for this part of our result
  26. *
  27. * @param {Function} onGenericArray
  28. * -> @param {Array} schema -- (this is always `[]`)
  29. * -> @param {String} parentKeyOrIndex
  30. * -> @returns {*} value for this part of our result
  31. *
  32. * @param {Function} onOther
  33. * -> @param {*} schema
  34. * -> @param {String} parentKeyOrIndex
  35. * -> @returns {*} value for this part of our result
  36. *
  37. * @return {Function}
  38. */
  39. module.exports = function buildIterator(onFacetDict, onPatternArray, onGenericDict, onGenericArray, onOther) {
  40. /**
  41. * @param {*} subSchema [description]
  42. * @param {} keyOrIndex [description]
  43. * @return {[type]} [description]
  44. */
  45. function _iterator(subSchema, keyOrIndex){
  46. if (_.isArray(subSchema)) {
  47. if (_.isEqual(subSchema, [])) {
  48. return onGenericArray(subSchema, keyOrIndex);
  49. }
  50. return onPatternArray(subSchema, keyOrIndex, function (nextSchema, nextIndex){
  51. return _iterator(nextSchema, nextIndex);
  52. });
  53. }
  54. else if (_.isObject(subSchema)) {
  55. if (_.isEqual(subSchema, {})) {
  56. return onGenericDict(subSchema, keyOrIndex);
  57. }
  58. return onFacetDict(subSchema, keyOrIndex, function (nextSchema, nextKey) {
  59. return _iterator(nextSchema, nextKey);
  60. });
  61. }
  62. else {
  63. return onOther(subSchema, keyOrIndex);
  64. }
  65. }
  66. /**
  67. * @param {*} thingToTraverse
  68. * @return {*}
  69. */
  70. return function (thingToTraverse){
  71. return _iterator(thingToTraverse);
  72. };
  73. };