Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. export function bufferFibonacci<T>(this: Observable<T>): Observable<T[]> {
  2. return this.lift(new BufferFibonacciOperator<T>());
  3. }
  4.  
  5. class BufferFibonacciOperator<T> implements Operator<T, T[]> {
  6.  
  7. call(subscriber: Subscriber<T[]>, source: any): any {
  8. return source.subscribe(new BufferFibonacciSubscriber(subscriber));
  9. }
  10. }
  11.  
  12. class BufferFibonacciSubscriber<T> extends Subscriber<T> {
  13. private buffers: Array<T[]> = [];
  14. private count: number = 0;
  15. private pageCount: number = 0;
  16.  
  17. constructor(destination: Subscriber<T[]>) {
  18. super(destination);
  19. }
  20.  
  21. protected _next(value: T) {
  22. const count = this.count++;
  23. const stepSize = this.fib(this.pageCount) * 100;
  24. const {destination, buffers} = this;
  25.  
  26. if (count === 0) {
  27. buffers.push([]);
  28. }
  29.  
  30. for (let i = buffers.length; i--;) {
  31. const buffer = buffers[i];
  32. buffer.push(value);
  33. if (buffer.length === stepSize) {
  34. buffers.splice(i, 1);
  35. destination.next(buffer);
  36. this.pageCount++;
  37. }
  38. }
  39. }
  40.  
  41. protected _complete() {
  42. const destination = this.destination;
  43. const buffers = this.buffers;
  44. while (buffers.length > 0) {
  45. let buffer = buffers.shift();
  46. if (buffer.length > 0) {
  47. destination.next(buffer);
  48. }
  49. }
  50. super._complete();
  51. }
  52.  
  53. private fib(i: number): number {
  54. return (i <= 2) ? 1 : this.fib(i - 1) + this.fib(i - 2);
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement