Created
May 31, 2016 16:47
-
-
Save msssk/2b05da97d54b50b433aa117ce0b80639 to your computer and use it in GitHub Desktop.
store with Immutable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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