-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyStore.js
73 lines (62 loc) · 2.12 KB
/
keyStore.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
const fs = require("fs")
class KeyStore {
constructor(path, parse, serializePair, serialize){
const dir = `${path}/relations`
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
this.parse = parse
this.serialize = serialize
this.serializePair = serializePair
this.dir = dir
}
getPath(file){
return this.dir + "/" + file + ".csv"
}
*getAllRelations(){
const files = fs.readdirSync(this.dir + "/")
for (const fn of files) yield fn.slice(0, fn.lastIndexOf(".csv"))
}
*iterate(){
for(const rel of this.getAllRelations()) yield this.get(rel)
}
has(file){
return fs.existsSync(this.getPath(file))
}
removeAllMentionsOf(i){
for(const name of this.getAllRelations()){
const fn = this.getPath(name)
const data = fs.readFileSync(fn).toString().split("\n")
const set = new Set()
for(const line of data){
if (line === "") continue
const [a, b] = line.split(", ")
if (parseInt(a) === i || parseInt(b) === i) continue
set.add(`${a}, ${b}`)
}
fs.writeFileSync(fn, [...set].join("\n") + "\n", {encoding:'utf8',flag:'w'})
}
}
get(name){
const path = this.getPath(name)
if (!(fs.existsSync(path))) throw `Index out of bounds ${name}`
const data = fs.readFileSync(path).toString()
return this.parse(name, data)
}
addPair(name, d1, d2){
const path = this.getPath(name)
fs.appendFileSync(path, this.serializePair(name, d1, d2) + "\n")
}
newRelation(name){
const path = this.getPath(name)
fs.writeFileSync(path, "", {encoding:'utf8',flag:'w'})
}
set(name, data){
const path = this.getPath(name)
const serializedData = this.serialize(data)
if (serializedData == "" || serializedData == "\n") {
fs.unlinkSync(path)
return
}
fs.writeFileSync(path, serializedData, {encoding:'utf8',flag:'w'})
}
}
module.exports = {KeyStore}