sample.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var typeInfo = require('./type-info');
  6. var coerce = require('./coerce');
  7. var dehydrate = require('./dehydrate');
  8. var isEqual = require('./is-equal');
  9. var buildSchemaIterator = require('./helpers/build-schema-iterator');
  10. /**
  11. * Given a type schema, return an array of up to `n` sample values for it, in random order.
  12. *
  13. * @param {String} typeSchema
  14. * @param {Number} n (defaults to 2)
  15. * @return {[===]}
  16. */
  17. module.exports = function sample (typeSchema, n) {
  18. // Default `n` to 2
  19. n = _.isUndefined(n) ? 2 : n;
  20. // Validate `n`
  21. if (n < 1 || !_.isNumber(n)) {
  22. throw new Error('rttc.sample() expects `n` (2nd argument) to be a number >= 1 indicating the number of sample values to generate.');
  23. }
  24. // Dehydrate the type schema to avoid circular recursion
  25. var dehydratedTypeSchema = dehydrate(typeSchema);
  26. // Configure type schema iterator
  27. var generateSampleVal = buildSchemaIterator(
  28. function onFacetDict(facetDictionary, parentKeyOrIndex, callRecursive){
  29. return _.reduce(facetDictionary, function (memo, val, key) {
  30. var facet = callRecursive(val, key);
  31. memo[key] = facet;
  32. return memo;
  33. }, {});
  34. },
  35. function onPatternArray(patternArray, parentKeyOrIndex, iterateRecursive){
  36. var pattern = iterateRecursive(patternArray[0], 0);
  37. return [ pattern ];
  38. },
  39. function onGenericDict(schema, parentKeyOrIndex){
  40. return {};
  41. },
  42. function onGenericArray(schema, parentKeyOrIndex){
  43. return [];
  44. },
  45. function onOther(schema, parentKeyOrIndex){
  46. // Pick a random example
  47. var example = _.sample(typeInfo(schema).getExamples());
  48. return example;
  49. }
  50. );
  51. // Generate some (unique) sample values
  52. var samples = _.reduce(_.range(n), function (samplesSoFar, i) {
  53. var newSample = generateSampleVal(dehydratedTypeSchema);
  54. var isUnique = _.reduce(samplesSoFar, function checkUniqueness(isUnique, existingSample){
  55. return isUnique && !isEqual(existingSample, newSample, typeSchema);
  56. }, true);
  57. if (isUnique) {
  58. samplesSoFar.push(newSample);
  59. }
  60. return samplesSoFar;
  61. }, []);
  62. // Scramble them and return.
  63. return _.shuffle(samples);
  64. };