Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created October 20, 2014 03:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/3c72613da39c569fe752 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/3c72613da39c569fe752 to your computer and use it in GitHub Desktop.
Transducer support coming in 2.3.14
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) { xform.step(observer, v);},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
});
};
var Rx = require('rx');
var t1 = require('transducers-js');
var t2 = require('transducers.js');
function even (x) { return x % 2 === 0; }
function mul10(x) { return x * 10; }
// Using cognitect's transducers
Rx.Observable.range(1, 5)
.transduce(t1.comp(t1.filter(even), t1.map(mul10)))
.subscribeOnNext(function (x) {
console.log('Cognitect Next: %d', x);
});
// => Cognitect Next: 20
// => Cognitect Next: 40
// Using jlongster's transducers
Rx.Observable.range(1, 5)
.transduce(t2.compose(t2.filter(even), t2.map(mul10)))
.subscribeOnNext(function (x) {
console.log('jLongster Next: %d', x);
});
// => jLongster Next: 20
// => jLongster Next: 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment