combine.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var 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 function (info) {
  15. var obj = info;
  16. for (var 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(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\n'));
  33. }
  34. return true;
  35. }
  36. /*
  37. * function combine (info)
  38. * Returns a new instance of the combine Format which combines the specified
  39. * formats into a new format. This is similar to a pipe-chain in transform streams.
  40. * We choose to combine the prototypes this way because there is no back pressure in
  41. * an in-memory transform chain.
  42. */
  43. module.exports = function () {
  44. for (var _len = arguments.length, formats = Array(_len), _key = 0; _key < _len; _key++) {
  45. formats[_key] = arguments[_key];
  46. }
  47. var combinedFormat = format(cascade(formats));
  48. var instance = combinedFormat();
  49. instance.Format = combinedFormat.Format;
  50. return instance;
  51. };
  52. //
  53. // Export the cascade method for use in cli and other
  54. // combined formats that should not be assumed to be
  55. // singletons.
  56. //
  57. module.exports.cascade = cascade;