/
index.js
82 lines (64 loc) · 1.75 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
"use strict";
const path = require("path");
const fs = require("fs");
const has = require("mout/object/has");
const keys = require("mout/object/keys");
const unset = require("mout/object/unset");
const dataPath = "data";
class Vote {
constructor(){
this.data = {} ;
}
getDataPath(){
return path.join(dataPath, "data.json");
}
save(){
var data = JSON.stringify(this.data);
fs.writeFileSync(this.getDataPath() , data);
}
load(){
var data = {};
try{
fs.accessSync(getDataPath() , fs.R_OK | fs.W_OK);
let d = fs.readFileSync(getDataPath());
data = JSON.parse(d);
}catch(e){
console.log("cant access data");
}
return data;
}
for(field, candidateId){
if(!field || !candidateId)
return false;
if(!has(this.data , field + "." + candidateId))
return false;
this.data[field][candidateId]["score"] = this.data[field][candidateId]["score"] || 0;
this.data[field][candidateId]["score"]++;
return true;
}
createCandidate(field , candidate){
if(!this.data[field])
return console.warn("field not exist");
if(!candidate || candidate.id)
return console.warn("condidate must have id");
if(has(this.data , field + "." + candidate.id))
return console.warn("condidate allrady exist");
this.data[field][candidate.id] = {info : candidate};
}
reset(){
this.data = {};
}
resetField(field){
return unset(this.data, field);
}
getAllFiled(){
return keys(this.data);
}
getCandidates(field){
return keys(this.data[field] || {})
}
getRanck(field , candidate){
//todo implement this methode
}
};
module.exports = Vote;