Odd Tens Observable
by gladtocode
HTML
<body>
Values:
</body>
JavaScript
const print = (value) => {
const paragraph = document.createElement('p');
paragraph.innerHTML = value;
document.body.appendChild(paragraph);
}
const integerObservable = (observer) => {
let x = 0;
setInterval(
() => {
x = x + 1;
observer(x);
},
500
);
};
const ignoreEvenOperator = (originalObservable) => {
return (observer) => {
originalObservable((originalValue) => {
if (originalValue % 2 == 1) {
// Only emit the value if it is odd
observer(originalValue);
}
});
}
}
const multiplyOperator = (originalObservable, multiplier) => {
return function(observer) {
// Our internalObserver observes the original stream, and for each
// value emitted, we emit a corresponding value -- the original value
// multipled by the specified multplier
const internalObserver = (value) => observer(value * multiplier);
originalObservable(internalObserver);
}
}
class Observable {
constructor(observableFunction) {
this.observableFunction = observableFunction;
this.subscribe = this.subscribe.bind(this);
}
subscribe(observer) {
return this.observableFunction(observer);
}
multiply(multiplier) {
return new Observable(multiplyOperator(this.observableFunction, multiplier));
}
ignoreEven() {
return new Observable(ignoreEvenOperator(this.observableFunction));
}
}
const observable = new Observable(integerObservable)
observable.ignoreEven().multiply(10).subscribe(print);