Skip to content

Instantly share code, notes, and snippets.

@jinjor
Created February 1, 2015 04:50
Show Gist options
  • Save jinjor/f0eba69547dc53b1d1e8 to your computer and use it in GitHub Desktop.
Save jinjor/f0eba69547dc53b1d1e8 to your computer and use it in GitHub Desktop.
Flyweight
var Flyweight = function() {
this._all = null;
this._indexed = null;
};
Flyweight.prototype._fetch = function() {
console.log('fetch');
return Promise.resolve([{
_id: 1
}]);
};
Flyweight.prototype.findAll = function() {
if (this._all) {
return Promise.resolve(this._all);
} else {
return this._fetch().then(function(all) {
this._all = all;
return Promise.resolve(this._all);
}.bind(this));
}
};
Flyweight.prototype._indexedAll = function() {
if (this._indexed) {
return Promise.resolve(this._indexed);
}
return this.findAll().then(function() {
var all = this._all;
this._indexed = {};
for (var i = 0; i < all.length; i++) {
this._indexed[all[i]._id] = all[i];
}
return Promise.resolve(this._indexed);
}.bind(this));
};
Flyweight.prototype.find = function(id) {
return this._indexedAll().then(function(indexed) {
return Promise.resolve(indexed[id]);
});
};
Flyweight.prototype.reset = function(id) {
this._all = null;
this._indexed = null;
};
var fw = new Flyweight()
fw.find(2).then(function(obj) {
console.log(obj);
fw.find(1).then(function(obj) {
console.log(obj);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment