Skip to content

Instantly share code, notes, and snippets.

@thebigredgeek
Created September 2, 2015 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebigredgeek/11348ea2791f9f1b59e2 to your computer and use it in GitHub Desktop.
Save thebigredgeek/11348ea2791f9f1b59e2 to your computer and use it in GitHub Desktop.
map/reduce - promises vs reactive programming
{
"data": [
{
"value": 1
},
{
"value": 2
},
{
"value": 3
},
{
"value": 4
}
]
}
//Here, let's assume that the data above is sent, one object at a time, from the backend via web sockets or long polling
//This is very useful for when you don't know the entire set, or when the set is mutable.
//Not only can we pipe the initial set to the client, but we can also push state mutations to the objects and the collection
//one object at a time!
var s = getSomeRealtimeStream();
s.on('data', function (data) {
var val = _.chain(data) //impossible to move to separate thread. all one big operation
.pluck('value')
.reduce(function(sum, value){
return sum + value;
}, 0)
.value();
console.log(val);
});
//This is for a one-time response, like HTTP requests
var p = getData(); //Assume this returns a promise with the response being data.json
p
.then(function(response){ //all hard to move to separate thread
return response.data; //first, lets traverse to the data property
})
.then(function(data){
return _.pluck(data, 'value'); //underscore#pluck - returns a new array of [1, 2, 3, 4]
})
.then(function(values){
return _.reduce(values, function(sum, value){
return sum + value;
}, 0); //set sum to zero at start
})
.then(function(sum){
console.log(sum); // => 10
})
//This is for a one-time response, like HTTP requests
var p = getData(); //Assume this returns a promise with the response being data.json
someReactiveLib.fromPromise(p)
.traverse('data') //any one of these steps in the stream could be offloaded onto a separate thread while retaining flow
.pluck('value')
.reduceAsSum() //sugar method for reduce
.type('int') //optional type cast
.toPromise()
.then(function(sum){
console.log(sum); // => 10
}, function (error) {
console.error(error); // => output of error with pointer to malfunctioning step in case something went wrong
});
//Here, let's assume that the data above is sent, one object at a time, from the backend via web sockets or long polling
//This is very useful for when you don't know the entire set, or when the set is mutable.
//Not only can we pipe the initial set to the client, but we can also push state mutations to the objects and the collection
//one object at a time!
var s = getSomeRealtimeStream();
s //for each incoming value
.pluck('value') //all possible to offload to separate thread. completely async
.reduceAsSum()
.type('int')
.pipe(console.log); //send output to console as it comes through
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment