Skip to content

Instantly share code, notes, and snippets.

@Xanir Xanir/GroupedGet
Last active Apr 25, 2017

Embed
What would you like to do?
GroupedGet
var GroupedGet = function(getterFn, massGetterFn) {
var thisGroupService = this;
thisGroupService._items = {};
thisGroupService._pendingItems = {};
thisGroupService._singleGet = getterFn;
thisGroupService._massGet = massGetterFn;
thisGroupService.sendMassGet = thisGroupService.sendMassGet.bind(this);
thisGroupService.get = thisGroupService.get.bind(this);
};
GroupedGet.prototype._wait = 50;
GroupedGet.prototype._max = 10;
GroupedGet.prototype.createPromise = function() {
var defer = {};
defer.promise = new Promise(function(resolve, reject) {
defer.resolve = resolve;
defer.reject = reject;
});
return defer;
};
GroupedGet.prototype.sendMassGet = function() {
var thisGroupService = this;
var ids = Object.keys(thisGroupService._pendingItems);
if (ids.length) {
thisGroupService._pendingItems = {};
thisGroupService._massGet(ids).then(
function() {
ids.forEach(function(id) {
thisGroupService._items[id].resolve();
});
},
function() {
ids.forEach(function(id) {
thisGroupService._items[id].reject();
});
}
);
}
};
GroupedGet.prototype.get = function(id) {
var thisGroupService = this;
var promiseForId = thisGroupService._items[id];
if (promiseForId) {
return promiseForId.promise;
}
var promiseForId = thisGroupService.createPromise();
thisGroupService._items[id] = promiseForId;
thisGroupService._pendingItems[id] = promiseForId;
promiseForId.promise = promiseForId.promise.then(
function() {
delete thisGroupService._items[id];
var item = thisGroupService._singleGet(id);
return item;
},
function() {
delete thisGroupService._items[id];
}
);
window.clearTimeout(thisGroupService._debounceId);
var ids = Object.keys(thisGroupService._pendingItems);
if (ids.length >= thisGroupService._max) {
thisGroupService.sendMassGet();
} else {
thisGroupService._debounceId = window.setTimeout(function() {
thisGroupService.sendMassGet();
}, thisGroupService._wait);
}
return promiseForId.promise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.