Created
October 20, 2014 03:34
-
-
Save mattpodwysocki/3c72613da39c569fe752 to your computer and use it in GitHub Desktop.
Transducer support coming in 2.3.14
This file contains 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
/** | |
* 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); } | |
); | |
}); | |
}; |
This file contains 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
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