-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.js
77 lines (66 loc) · 1.94 KB
/
list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var mxtend = require('xtend/mutable')
var inherits = require('inherits')
var Store = require('./')
var _ = {
sortedLastIndexBy: require('lodash/sortedLastIndexBy'),
remove: function remove (list, item) {
var i = list.indexOf(item)
if (i > -1) list.splice(i, 1)
return list
}
}
// abstract store for lists of things
function ListStore (args) {
if (!(this instanceof ListStore)) return new ListStore(args)
Store.call(this, args)
}
inherits(ListStore, Store)
mxtend(ListStore.prototype, {
idKey: 'id',
sortBy: 'id',
_state: {
data: {},
sorted: [],
hasFetched: false
},
add: function (item) {
var self = this
self._state.data[item[self.idKey]] = item
var i = _.sortedLastIndexBy(self._state.sorted, item, function (item) {
return item[self.sortBy]
})
self._state.sorted.splice(i, 0, item)
return self.publish()
},
edit: function (newData) {
if (!this._state.data[newData[this.idKey]]) return this
mxtend(this._state.data[newData[this.idKey]], newData)
return this.publish()
},
get: function (items) {
var self = this
this._state.hasFetched = true
this._state.data = items.reduce(function (acc, ev) {
acc[ev[self.idKey]] = ev
return acc
}, {})
this._state.sorted = items
return this.publish()
},
delete: function (item) {
if (this._state.data[item[this.idKey]]) {
var _item = this._state.data[item[this.idKey]]
delete this._state.data[item[this.idKey]]
_.remove(this._state.sorted, _item)
return this.publish()
}
return this
}
})
ListStore.contains = function (store, item) {
return !!store._state.data[item[store.idKey]]
}
ListStore.extend = function (opts) {
return Store.extend(opts, ListStore)
}
module.exports = ListStore