Created
March 21, 2017 04:10
-
-
Save rbellamy/3857bbbf2aa556bcde8ecb5d1d3d6556 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function bufferFibonacci<T>(this: Observable<T>): Observable<T[]> { | |
return this.lift(new BufferFibonacciOperator<T>()); | |
} | |
class BufferFibonacciOperator<T> implements Operator<T, T[]> { | |
call(subscriber: Subscriber<T[]>, source: any): any { | |
return source.subscribe(new BufferFibonacciSubscriber(subscriber)); | |
} | |
} | |
class BufferFibonacciSubscriber<T> extends Subscriber<T> { | |
private buffers: Array<T[]> = []; | |
private count: number = 0; | |
private pageCount: number = 0; | |
constructor(destination: Subscriber<T[]>) { | |
super(destination); | |
} | |
protected _next(value: T) { | |
const count = this.count++; | |
const stepSize = this.fib(this.pageCount) * 100; | |
const {destination, buffers} = this; | |
if (count === 0) { | |
buffers.push([]); | |
} | |
for (let i = buffers.length; i--;) { | |
const buffer = buffers[i]; | |
buffer.push(value); | |
if (buffer.length === stepSize) { | |
buffers.splice(i, 1); | |
destination.next(buffer); | |
this.pageCount++; | |
} | |
} | |
} | |
protected _complete() { | |
const destination = this.destination; | |
const buffers = this.buffers; | |
while (buffers.length > 0) { | |
let buffer = buffers.shift(); | |
if (buffer.length > 0) { | |
destination.next(buffer); | |
} | |
} | |
super._complete(); | |
} | |
private fib(i: number): number { | |
return (i <= 2) ? 1 : this.fib(i - 1) + this.fib(i - 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment