Skip to content

Instantly share code, notes, and snippets.

@trxcllnt
Last active December 16, 2015 06:28
Show Gist options
  • Save trxcllnt/5391436 to your computer and use it in GitHub Desktop.
Save trxcllnt/5391436 to your computer and use it in GitHub Desktop.
/*
Observable.mappend maps a value through a selector and returns
a unique Array of the input values and the result(s).
Use mappend when you'd rather not create anonymous value types
just to track the IObservable stream inputs. Takes advantage of
JS's ability to apply an Array as function arguments, giving the
benefit of more readable JS methods.
Pros:
- Takes advantage of JS native functionality.
- Less typing.
- Can select over value types with Array methods. Ex: "obs.map(tail)"
to slice the first argument out of the value.
- Reduces noise. The important functions (business logic/subscriptions)
are more readable.
Cons:
Arrays are indexed, not named, sequence matters.
*/
var combine = function(...args) {
return Array.prototype.concat.apply([], args);
};
var distribute = function(f) {
return function(a) {
return f.apply(null, a);
};
};
var sum = function(a, b) { return a + b; };
Rx.Observable.mappend = function(selector) {
return this.map(function() {
var selection = selector.apply(null, arguments);
var results = [];
combine(arguments, selection).forEach(function(e) {
if(results.indexOf(e) != -1) return;
results[results.length] = e;
});
return results;
});
};
var singles = Rx.Observable.range(0, 10);
var doubles = Rx.Observable.range(10, 20);
var sums = singles.combineLatest(doubles, combine).mappend(distribute(sum));
sums.subscribe(distribute(function(a, b, c) {
console.log('the sum of', a, 'and', b, 'is', c);
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment