-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
121 lines (119 loc) · 2.7 KB
/
index.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
const fs = require('fs')
class DB {
constructor(file='DB.json', options={}) {
this.file = file ?? 'DB.json';
if (!fs.existsSync(this.file)) {
this._setFile({});
}
this.compact = Boolean(options?.compact);
}
_getFile() {
let contents = fs.readFileSync(this.file, 'utf8');
try {
contents = JSON.parse(contents);
} catch (err) {
throw new Error(this.file + ' is corrupted');
}
return contents;
}
_setFile(contents, file=this.file) {
fs.writeFileSync(file,
(this.compact ?
JSON.stringify(contents) :
JSON.stringify(contents, null, 2)),
{ overwrite: true });
}
_setnest(data, key, value) {
let p = key.split('.');
let target = data;
for (let i = 0; i < p.length - 1; i++) {
if (target[p[i]] === undefined) {
target[p[i]] = {};
}
target = target[p[i]];
}
target[p[p.length - 1]] = value;
return data;
}
set(key, value) {
let data = this._getFile();
data = this._setnest(data, key, value)
this._setFile(data);
}
get(key) {
let data = this._getFile();
let p = key.split('.');
for (let i= 0; i < p.length; i++) {
data = data[p[i]]
}
return data
}
has(key) {
let data = this._getFile();
return data[key] !== undefined;
}
remove(key) {
let data = this._getFile();
delete data[key];
this._setFile(data);
}
find(func) {
let data = this._getFile();
let match = [];
Object.keys(data).forEach(key => {
if (func(data[key], key)) {
match.push(key)
}
})
return match;
}
keys() {
return Object.keys(this._getFile())
}
values() {
return Object.values(this._getFile())
}
all() {
return this._getFile()
}
backup(file) {
this._setFile(this._getFile(), file);
}
add(key, number) {
let data = this._getFile();
data[key] = (Number(data[key]) || 0) + number;
this._setFile(data);
}
sub(key, number) {
let data = this._getFile();
data[key] = (Number(data[key]) || 0) - number;
this._setFile(data);
}
push(key, value) {
let data = this._getFile();
data[key].push(value)
this._setFile(data);
}
pull(key, index) {
let data = this._getFile();
data[key] = data[key].slice(0,index).concat(data[key].slice(index+1,data[key].length))
this._setFile(data);
}
pop(key) {
let data = this._getFile();
let value = data[key].pop()
this._setFile(data);
return value;
}
flat(key) {
let data = this._getFile();
data[key] = data[key].flat()
this._setFile(data);
}
concat(key, value) {
let data = this._getFile();
data[key] = data[key].concat(value)
this._setFile(data);
}
}
module.exports = DB;