Stream.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include <functional>
  3. #include "Supplier.h"
  4. namespace Framework
  5. {
  6. template<typename T> class Stream
  7. {
  8. private:
  9. Supplier<T>* supplier;
  10. public:
  11. Stream(Supplier<T>* supplier)
  12. : supplier(supplier)
  13. {}
  14. ~Stream()
  15. {
  16. supplier->release();
  17. }
  18. Stream<T> filter(std::function<bool(T)> f)
  19. {
  20. return Stream<T>(new FilteredSupplier<T>(
  21. dynamic_cast<Supplier<T>*>(supplier->getThis()), f));
  22. }
  23. template<typename R> Stream<R> map(std::function<R(T)> f)
  24. {
  25. return Stream<R>(new MappedSupplier<T, R>(
  26. dynamic_cast<Supplier<T>*>(supplier->getThis()), f));
  27. }
  28. template<typename R> Stream<R> flatMap(std::function<Stream<R>(T)> f)
  29. {
  30. return Stream<R>(new FlatMappedSupplier<T, R>(
  31. dynamic_cast<Supplier<T>*>(supplier->getThis()),
  32. [this, f](T arg) {
  33. return dynamic_cast<Supplier<R>*>(
  34. f(arg).zSupplier()->getThis());
  35. }));
  36. }
  37. void forEach(std::function<void(T)> action)
  38. {
  39. while (true)
  40. {
  41. try
  42. {
  43. action(supplier->next());
  44. } catch (Exceptions::EndOfSupplier)
  45. {
  46. return;
  47. }
  48. }
  49. }
  50. template<typename R>
  51. R collect(std::function<R(R, T)> combinator, R initialValue)
  52. {
  53. while (true)
  54. {
  55. try
  56. {
  57. initialValue = combinator(initialValue, supplier->next());
  58. } catch (Exceptions::EndOfSupplier)
  59. {
  60. return initialValue;
  61. }
  62. }
  63. }
  64. Supplier<T>* zSupplier()
  65. {
  66. return supplier;
  67. }
  68. };
  69. } // namespace Framework