Skip to content

Instantly share code, notes, and snippets.

@smart--petea
Created April 13, 2017 13:55
Show Gist options
  • Save smart--petea/d51d632298cc3416d59eec306abd9312 to your computer and use it in GitHub Desktop.
Save smart--petea/d51d632298cc3416d59eec306abd9312 to your computer and use it in GitHub Desktop.
Optimized sequential if/else pattern for Rx observables. (see generateObservableOptimized)
/// <reference path="typings/globals/es6-shim/index.d.ts" />`
import * as Rx from 'rxjs';
function generateObservable(...args) {
return Rx.Observable.of({
count: arguments.length > 1 ? 0 : 1
});
}
//non-optimized variant
generateObservable('a', 'b', 'c', 'd').
flatMap(
x => {
if(x.count == 0) return generateObservable('a', 'b', 'c').flatMap(
y => {
if(y.count == 0) {
return generateObservable('a', 'b').flatMap(
z => {
if(z.count == 0) return generateObservable('a');
return Rx.Observable.of(z);
}
);
}
return Rx.Observable.of(y);
}
);
return Rx.Observable.of(x);
}
).
subscribe(console.log);
//optimized variant. developed with Sereoga
function generateObservableOptimized(...args: Array<any>) {
return generateObservable.apply(null, args).flatMap(x => {
if (x.count == 0) {
return generateObservableOptimized.apply(null, args.slice(0, args.length - 1));
}
return Rx.Observable.of(x);
});
}
generateObservableOptimized('a', 'b', 'c').subscribe(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment