helpers.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. var assert = require('assert');
  3. var filter = require('arr-filter');
  4. var map = require('arr-map');
  5. var flatten = require('arr-flatten');
  6. var forEach = require('array-each');
  7. function noop() {}
  8. function getExtensions(lastArg) {
  9. if (typeof lastArg !== 'function') {
  10. return lastArg;
  11. }
  12. }
  13. function filterSuccess(elem) {
  14. return elem.state === 'success';
  15. }
  16. function filterError(elem) {
  17. return elem.state === 'error';
  18. }
  19. function buildOnSettled(done) {
  20. if (typeof done !== 'function') {
  21. done = noop;
  22. }
  23. function onSettled(error, result) {
  24. if (error) {
  25. return done(error, null);
  26. }
  27. var settledErrors = filter(result, filterError);
  28. var settledResults = filter(result, filterSuccess);
  29. var errors = null;
  30. if (settledErrors.length) {
  31. errors = map(settledErrors, 'value');
  32. }
  33. var results = null;
  34. if (settledResults.length) {
  35. results = map(settledResults, 'value');
  36. }
  37. done(errors, results);
  38. }
  39. return onSettled;
  40. }
  41. function verifyArguments(args) {
  42. args = flatten(args);
  43. var lastIdx = args.length - 1;
  44. assert.ok(args.length, 'A set of functions to combine is required');
  45. forEach(args, function(arg, argIdx) {
  46. var isFunction = typeof arg === 'function';
  47. if (isFunction) {
  48. return;
  49. }
  50. if (argIdx === lastIdx) {
  51. // Last arg can be an object of extension points
  52. return;
  53. }
  54. var msg = 'Only functions can be combined, got ' + typeof arg +
  55. ' for argument ' + argIdx;
  56. assert.ok(isFunction, msg);
  57. });
  58. return args;
  59. }
  60. module.exports = {
  61. getExtensions: getExtensions,
  62. onSettled: buildOnSettled,
  63. verifyArguments: verifyArguments,
  64. };