combine.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const format = require('./format');
  3. /*
  4. * function cascade(formats)
  5. * Returns a function that invokes the `._format` function in-order
  6. * for the specified set of `formats`. In this manner we say that Formats
  7. * are "pipe-like", but not a pure pumpify implementation. Since there is no back
  8. * pressure we can remove all of the "readable" plumbing in Node streams.
  9. */
  10. function cascade(formats) {
  11. if (!formats.every(isValidFormat)) {
  12. return;
  13. }
  14. return info => {
  15. let obj = info;
  16. for (let i = 0; i < formats.length; i++) {
  17. obj = formats[i].transform(obj, formats[i].options);
  18. if (!obj) {
  19. return false;
  20. }
  21. }
  22. return obj;
  23. };
  24. }
  25. /*
  26. * function isValidFormat(format)
  27. * If the format does not define a `transform` function throw an error
  28. * with more detailed usage.
  29. */
  30. function isValidFormat(fmt) {
  31. if (typeof fmt.transform !== 'function') {
  32. throw new Error([
  33. 'No transform function found on format. Did you create a format instance?',
  34. 'const myFormat = format(formatFn);',
  35. 'const instance = myFormat();'
  36. ].join('\n'));
  37. }
  38. return true;
  39. }
  40. /*
  41. * function combine (info)
  42. * Returns a new instance of the combine Format which combines the specified
  43. * formats into a new format. This is similar to a pipe-chain in transform streams.
  44. * We choose to combine the prototypes this way because there is no back pressure in
  45. * an in-memory transform chain.
  46. */
  47. module.exports = (...formats) => {
  48. const combinedFormat = format(cascade(formats));
  49. const instance = combinedFormat();
  50. instance.Format = combinedFormat.Format;
  51. return instance;
  52. };
  53. //
  54. // Export the cascade method for use in cli and other
  55. // combined formats that should not be assumed to be
  56. // singletons.
  57. //
  58. module.exports.cascade = cascade;