-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocaldb.js
100 lines (98 loc) · 2.88 KB
/
localdb.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
/******************************************************************************
LOCALDB COMPONENT
******************************************************************************/
module.exports = localdb
function localdb () {
const prefix = '153/'
return { add, read_all, read, drop, push, length, append, find }
function length (keys) {
const address = prefix + keys.join('/')
return Object.keys(localStorage).filter(key => key.includes(address)).length
}
/**
* Assigns value to the key of an object already present in the DB
*
* @param {String[]} keys
* @param {any} value
*/
function add (keys, value, precheck) {
localStorage[(precheck ? '' : prefix) + keys.join('/')] = JSON.stringify(value)
}
/**
* Appends values into an object already present in the DB
*
* @param {String[]} keys
* @param {any} value
*/
function append (keys, data) {
const pre = keys.join('/')
Object.entries(data).forEach(([key, value]) => {
localStorage[prefix + pre+'/'+key] = JSON.stringify(value)
})
}
/**
* Pushes value to an array already present in the DB
*
* @param {String[]} keys
* @param {any} value
*/
function push (keys, value) {
const data = JSON.parse(localStorage[keys[0]])
let temp = data
keys.slice(1).forEach(key => {
temp = temp[key]
})
temp.push(value)
localStorage[keys[0]] = JSON.stringify(data)
}
function read (keys) {
const result = localStorage[prefix + keys.join('/')]
return result && JSON.parse(result)
}
function read_all (keys) {
const address = prefix + keys.join('/')
let result = {}
Object.entries(localStorage).forEach(([key, value]) => {
if(key.includes(address))
result[key.split('/').at(-1)] = JSON.parse(value)
})
return result
}
function drop (keys) {
if(keys.length > 1){
const data = JSON.parse(localStorage[keys[0]])
let temp = data
keys.slice(1, -1).forEach(key => {
temp = temp[key]
})
if(Array.isArray(temp))
temp.splice(keys[keys.length - 1], 1)
else
delete(temp[keys[keys.length - 1]])
localStorage[keys[0]] = JSON.stringify(data)
}
else
delete(localStorage[keys[0]])
}
function find (keys, filters, index = 0) {
let index_count = 0
const address = prefix + keys.join('/')
const target_key = Object.keys(localStorage).find(key => {
if(key.includes(address)){
const entry = JSON.parse(localStorage[key])
let count = 0
Object.entries(filters).some(([search_key, value]) => {
if(entry[search_key] !== value)
return
count++
})
if(count === Object.keys(filters).length){
if(index_count === index)
return key
index_count++
}
}
}, undefined)
return target_key && JSON.parse(localStorage[target_key])
}
}