Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

toArray.ts 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { reduce } from './reduce';
  2. import { OperatorFunction } from '../types';
  3. function toArrayReducer<T>(arr: T[], item: T, index: number) {
  4. if (index === 0) {
  5. return [item];
  6. }
  7. arr.push(item);
  8. return arr;
  9. }
  10. /**
  11. * Collects all source emissions and emits them as an array when the source completes.
  12. *
  13. * <span class="informal">Get all values inside an array when the source completes</span>
  14. *
  15. * ![](toArray.png)
  16. *
  17. * `toArray` will wait until the source Observable completes before emitting
  18. * the array containing all emissions. When the source Observable errors no
  19. * array will be emitted.
  20. *
  21. * ## Example
  22. * ```ts
  23. * import { interval } from 'rxjs';
  24. * import { toArray, take } from 'rxjs/operators';
  25. *
  26. * const source = interval(1000);
  27. * const example = source.pipe(
  28. * take(10),
  29. * toArray()
  30. * );
  31. *
  32. * const subscribe = example.subscribe(val => console.log(val));
  33. *
  34. * // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  35. *
  36. * ```
  37. * @return An array from an observable sequence.
  38. * @method toArray
  39. * @owner Observable
  40. */
  41. export function toArray<T>(): OperatorFunction<T, T[]> {
  42. return reduce(toArrayReducer, [] as T[]);
  43. }