Skip to content

Instantly share code, notes, and snippets.

@Xanir
Last active April 25, 2017 14:53
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 Xanir/625539e31ee422ae890eae511bdd635f to your computer and use it in GitHub Desktop.
Save Xanir/625539e31ee422ae890eae511bdd635f to your computer and use it in GitHub Desktop.
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