-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathls-collection.js
112 lines (90 loc) · 2.59 KB
/
ls-collection.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
/*
Developed By: Md.Harun-Ur-Rashid
Country : Bangladesh
Github : http://github.com/haruncpi
*/
"use strict";
function lsCollection(keyName) {
if (!keyName || keyName === '') throw "a key name required for data sotre"
this.keyName = keyName
}
lsCollection.prototype = {
generateId: function () {
return Date.now()
},
getAll: function () {
var items = localStorage.getItem(this.keyName);
items = JSON.parse(items);
return items ? items : [];
},
insert: function (obj) {
if (typeof obj !== 'object') throw "object required, given " + typeof obj;
var id = this.generateId();
var items = this.getAll();
obj._id = id
items.push(obj)
localStorage.setItem(this.keyName, JSON.stringify(items))
return obj;
},
find: function (_id) {
if (typeof _id !== 'number') throw "_id must be numeric, given " + typeof _id;
return this.getAll().find(function (obj) {
return obj._id === _id
})
},
findWhere: function (findObj) {
if (typeof findObj !== 'object') throw "object required, given " + typeof findObj;
var items = this.getAll();
return items.find(function (item) {
return Object.keys(findObj).every(function (key) {
return item[key] === findObj[key]
})
})
},
where: function (findObj) {
if (typeof findObj !== 'object') throw "object required, given " + typeof findObj;
var items = this.getAll();
var matches = []
items.find(function (item) {
return Object.keys(findObj).every(function (key) {
if (item[key] === findObj[key]) {
matches.push(item)
}
})
})
return matches;
},
update: function (_id, updateData) {
if (typeof _id !== 'number') throw "_id must be numeric, given " + typeof _id;
var items = this.getAll()
var index = items.findIndex(function (item) {
return item._id === _id;
});
if (index !== -1) {
updateData._id = _id
items[index] = updateData;
localStorage.setItem(this.keyName, JSON.stringify(items));
return updateData;
} else {
return false;
}
},
delete: function (_id) {
if (typeof _id !== 'number') throw "_id must be numeric, given " + typeof _id;
var items = this.getAll()
var index = items.findIndex(function (item) {
return item._id === _id;
});
if (index !== -1) {
items.splice(index, 1);
localStorage.setItem(this.keyName, JSON.stringify(items))
return true
} else {
return false
}
},
flash: function () {
localStorage.removeItem(this.keyName);
console.log("flashed!")
}
}