Skip to content

Instantly share code, notes, and snippets.

@rzachariah
Created March 12, 2016 14:37
Show Gist options
  • Save rzachariah/a75d17450f7440086bad to your computer and use it in GitHub Desktop.
Save rzachariah/a75d17450f7440086bad to your computer and use it in GitHub Desktop.
// Imagine we have an observable of key counts. Each message has a key and a count, like so
// {
// key: "SomeKey",
// count: 16
// }
// We use buffer to convert this to an observable of arrays of messages
// Now we want to reduce each array, keeping only the latest count for each key
var messages = getKeyCountsObservablefromSomewhere()
.buffer(function () { return Rx.Observable.timer(50); })
.select(function(messages) {
if (messages.length === 0) return messages;
var hash = {};
messages.forEach(function(m) {
hash[m.key] = m.count;
})
console.log('hash', hash);
var uniqueMessages = [];
Object.keys(hash).forEach(function(key) {
uniqueMessages.push({key: key, count: hash[key]});
})
console.log('uniqueMessages', uniqueMessages);
return uniqueMessages;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment