Skip to content

Instantly share code, notes, and snippets.

@msssk
Created May 31, 2016 16:47
Show Gist options
  • Save msssk/2b05da97d54b50b433aa117ce0b80639 to your computer and use it in GitHub Desktop.
Save msssk/2b05da97d54b50b433aa117ce0b80639 to your computer and use it in GitHub Desktop.
store with Immutable
define([
'immutable/immutable',
], function (immutable) {
var MemoryStore = function MemoryStore () {
this.constructor.apply(this, arguments);
};
MemoryStore.prototype = {
constructor: function (options) {
options = options || {};
this._collection = immutable.fromJS(options.data);
},
get: function (id) {
return this._collection.get(id).toJS();
},
add: function (item) {
if (this._collection.has(item.id)) {
throw new Error('Item with id ' + item.id + ' already exists.');
}
// TODO: perhaps a reviver function passed to 'fromJS' can handle id properties
// named something other than 'id'
this._collection = this._collection.push(immutable.fromJS(item));
},
put: function (item) {
if (this._collection.has(item.id)) {
// TODO: maybe use 'update' or 'merge' methods?
this._collection = this._collection.set(item.id, item);
}
else {
this._collection = this._collection.push(immutable.fromJS(item));
}
},
delete: function (id) {
this._collection = this._collection.delete(id);
},
orderBy: function (name, descending) {
return this._collection.sort(function (valueA, valueB) {
if (valueA[name] < valueB[name]) {
return (descending ? 1 : -1);
}
else if (valueB[name] < valueA[name]) {
return (descending ? -1 : 1);
}
else {
return 0;
}
})
}
};
return MemoryStore;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment