Skip to content

Instantly share code, notes, and snippets.

@martinsson
Last active March 12, 2018 22:05
Show Gist options
  • Save martinsson/d93b7d83ca27ff1eff621b2e33556c57 to your computer and use it in GitHub Desktop.
Save martinsson/d93b7d83ca27ff1eff621b2e33556c57 to your computer and use it in GitHub Desktop.
Solving fibonacci in reactive streams. Why? Because it's possible :)
import {Observable} from "rxjs/Observable";
import {Subject} from "rxjs/Subject";
export function fibonacciStream() {
let fibN2: Subject<number> = new Subject();
// initiate the series, so that both this and fibN1 has atleast one
setImmediate(() => {
fibN2.next(0);
fibN2.next(1);
});
let sumOfPreviousTwo = Observable.zip(fibN2, fibN2.skip(1)) // common pattern to get successive values
.delay(0) // avoid infinite loop, by giving the event loop a chance
.map(([n2, n1]) => n2 + n1);
// this is the generating part
let initialTwoFibNumbers = Observable.from([0, 1]);
let fibN = initialTwoFibNumbers.concat(sumOfPreviousTwo);
return fibN.do(n => fibN2.next(n)); // feed fibN2 with fibN
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment