concat.js

  1. 'use strict';
  2. const { Each } = require('./each');
  3. const { concatArray } = require('./internal/util');
  4. const { setParallel } = require('./internal/collection');
  5. class Concat extends Each {
  6. constructor(collection, iterator) {
  7. super(collection, iterator, set);
  8. }
  9. _callResolve(value, index) {
  10. this._result[index] = value;
  11. if (--this._rest === 0) {
  12. this._promise._resolve(concatArray(this._result));
  13. }
  14. }
  15. }
  16. module.exports = { concat, Concat };
  17. function set(collection) {
  18. setParallel.call(this, collection);
  19. this._result = Array(this._rest);
  20. return this;
  21. }
  22. /**
  23. * `Aigle.concat` has almost the same functionality as `Array#concat`.
  24. * It iterates all elements of `collection` and executes `iterator` using each element on parallel.
  25. * The `iterator` needs to return a promise or something.
  26. * If a promise is returned, the function will wait until the promise is fulfilled.
  27. * Then the result will be assigned to an array, the role is the same as `Array#concat`.
  28. * All of them are finished, the function will return an array as a result.
  29. * @param {Array|Object} collection
  30. * @param {Function} iterator
  31. * @return {Aigle} Returns an Aigle instance
  32. * @example
  33. * const order = [];
  34. * const collection = [1, 4, 2];
  35. * const iterator = (num, index, collection) => {
  36. * return Aigle.delay(num * 10)
  37. * .then(() => {
  38. * order.push(num);
  39. * return num;
  40. * });
  41. * };
  42. * Aigle.concat(collection, iterator)
  43. * .then(array => {
  44. * console.log(array); // [1, 2, 4];
  45. * console.log(order); // [1, 2, 4];
  46. * });
  47. *
  48. * @example
  49. * const order = [];
  50. * const collection = { a: 1, b: 4, c: 2 };
  51. * const iterator = (num, key, collection) => {
  52. * return Aigle.delay(num * 10)
  53. * .then(() => {
  54. * order.push(num);
  55. * return num;
  56. * });
  57. * };
  58. * Aigle.concat(collection, iterator)
  59. * .then(array => {
  60. * console.log(array); // [1, 2, 4];
  61. * console.log(order); // [1, 2, 4];
  62. * });
  63. */
  64. function concat(collection, iterator) {
  65. return new Concat(collection, iterator)._execute();
  66. }