Guest User

Untitled

a guest
Jul 16th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. import { test } from 'ava';
  2. import * as Rx from 'rxjs';
  3. import { List } from 'immutable';
  4.  
  5. class State {
  6. private constructor(private lastN: List<number>, private num: number) {}
  7.  
  8. public static make(num: number): State { return new State(List(), num); }
  9.  
  10. public push(a: number): State {
  11. const newLast = List(this.lastN.push(a).slice(-this.num));
  12. return new State(newLast, this.num);
  13. }
  14.  
  15. public avg(): number {
  16. const sum = this.lastN.reduce((a, b) => a! + b!, 0);
  17. return sum / this.num;
  18. }
  19. }
  20.  
  21. test('feedback', async (t) => {
  22. const state = new Rx.Subject<State>();
  23.  
  24. const avgs = [] as number[];
  25.  
  26. const c = Rx.Observable.interval(100)
  27. .withLatestFrom(state)
  28. .map(([n, s]) => [n, s.push(n)] as [number, State])
  29. .do(([_, s]) => state.next(s))
  30. .take(6)
  31. .forEach(([_, s]) => avgs.push(s.avg()));
  32. // Provide first value to withLatestFrom.
  33. state.next(State.make(8));
  34. await c;
  35.  
  36. t.deepEqual(avgs, [0, 0.25, 0.75, 1.5, 2.5, 3.5, 4.5, 5.5]);
  37. });
Add Comment
Please, Sign In to add comment