Last active
March 12, 2018 22:05
-
-
Save martinsson/d93b7d83ca27ff1eff621b2e33556c57 to your computer and use it in GitHub Desktop.
Solving fibonacci in reactive streams. Why? Because it's possible :)
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
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