Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created August 27, 2014 21:08
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 mattpodwysocki/a5bbcba1567bff32fc77 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/a5bbcba1567bff32fc77 to your computer and use it in GitHub Desktop.
/**
* Converts the observable sequence to a WeakMap if it exists.
* @param {Function} keySelector A function which produces the key for the WeakMap
* @param {Function} [elementSelector] An optional function which produces the element for the WeakMap. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a WeakMap containing the values from the observable sequence.
*/
function toMap(source, type, keySelector, elementSelector) {
return new AnonymousObservable(function (observer) {
var m = new type();
return self.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
m.set(key, element);
},
observer.onError.bind(observer),
function () {
observer.onNext(m);
observer.onCompleted();
})
});
}
if (!!window.Map) {
Rx.Observable.prototype.toMap = function (keySelector, elementSelector) {
return toMap(this, window.Map, keySelector, elementSelector);
}
}
if (!!window.WeakMap) {
Rx.Observable.prototype.toWeakMap = function (keySelector, elementSelector) {
return toMap(this, window.WeakMap, keySelector, elementSelector);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment