reduce.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. describe('reduce', function()
  2. it('fails if the first argument is not a function', function()
  3. local observable = Rx.Observable.of(0)
  4. expect(observable:reduce()).to.fail()
  5. expect(observable:reduce(1)).to.fail()
  6. expect(observable:reduce('')).to.fail()
  7. expect(observable:reduce({})).to.fail()
  8. expect(observable:reduce(true)).to.fail()
  9. end)
  10. it('uses the seed as the initial value to the accumulator', function()
  11. local accumulator = spy()
  12. Rx.Observable.of(3):reduce(accumulator, 4):subscribe()
  13. expect(accumulator[1]).to.equal({4, 3})
  14. end)
  15. it('waits for 2 values before accumulating if the seed is nil', function()
  16. local accumulator = spy(function(x, y) return x * y end)
  17. local observable = Rx.Observable.fromTable({2, 4, 6}, ipairs):reduce(accumulator)
  18. expect(observable).to.produce(48)
  19. expect(accumulator).to.equal({{2, 4}, {8, 6}})
  20. end)
  21. it('uses the return value of the accumulator as the next input to the accumulator', function()
  22. local accumulator = spy(function(x, y) return x + y end)
  23. local observable = Rx.Observable.fromTable({1, 2, 3}, ipairs):reduce(accumulator, 0)
  24. expect(observable).to.produce(6)
  25. expect(accumulator).to.equal({{0, 1}, {1, 2}, {3, 3}})
  26. end)
  27. it('passes all produced values to the accumulator', function()
  28. local accumulator = spy(function() return 0 end)
  29. local observable = Rx.Observable.fromTable({2, 3, 4}, ipairs, true):reduce(accumulator, 0):subscribe()
  30. expect(accumulator).to.equal({{0, 2, 1}, {0, 3, 2}, {0, 4, 3}})
  31. end)
  32. it('calls onError if the accumulator errors', function()
  33. local onError = spy()
  34. Rx.Observable.fromRange(3):reduce(error):subscribe(nil, onError, nil)
  35. expect(#onError).to.equal(1)
  36. end)
  37. end)