-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.js
125 lines (103 loc) · 2.28 KB
/
model.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'use strict';
class Model {
/**
* @constructor
* @param data {string}
* @param save {function}
*/
constructor(data, save) {
try {
this.data = JSON.parse(data) || {};
}
catch (e) {
throw new Error('Invalid data');
}
this.save = () => save(this.data);
this.nextId = Math.max.apply(Math, Object.keys(this.data).concat([-1])) + 1;
}
/**
* @param id {number}
* @returns {Object|undefined} Found entry.
*/
get(id) {
return this.data[id];
}
/**
* @param entry {Object|Array<Object>}
* @returns {number|Array<number>} Added entry id.
*/
add(entry) {
var isArray = Array.isArray(entry);
var entries = isArray ? entry : [entry];
var ids = entries.map((entry) => {
var id = entry.id = this.nextId;
this.data[id] = entry;
this.nextId += 1;
return id;
});
return isArray ? ids : ids[0];
}
/**
* @param id {number|Object}
* @param [data] {Object}
* @returns {number} Updated entry id.
*/
update(id, data) {
if (data === void 0) {
data = id;
id = data.id;
}
if (id == null) {
throw new Error('id is not specified');
}
data.id = id;
this.data[id] = data;
return id;
}
/**
* @param id {number|Array<number>}
* @returns {number|Array<number>} Updated entry id.
*/
remove(id) {
var isArray = Array.isArray(id);
var ids = isArray ? id : [id];
var data = this.data;
ids.forEach(function(id) {
delete data[id];
});
return isArray ? ids : id;
}
/**
* @returns {Array<number>} List of ids.
*/
clear() {
var ids = Object.keys(this.data).map(Number);
this.data = {};
return ids;
}
/**
* @param [criteria] {Object}
* @returns {Array<Object>}
*/
find(criteria) {
var data = this.data;
var keys = Object.keys(data);
if (criteria) {
var result = [];
keys.forEach(function(key) {
var entry = data[key];
for (var prop in criteria) {
if (criteria.hasOwnProperty(prop)) {
if (entry[prop] === criteria[prop]) {
result.push(entry);
break;
}
}
}
});
return result;
}
return keys.map(key => data[key]);
}
}
module.exports = Model;