-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
99 lines (84 loc) · 2.81 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
const equal = require('lodash.isequal');
const Eot = require('eloquent-object-tools');
const eot = new(Eot);
class VanillaState {
constructor(stateObject, items, saveCallBack) {
this.objectHandler = {
saveCallBack,
stateObject,
stateObjectSave: eot.clone(stateObject),
items: (items || Object.keys(stateObject)),
versionHistory: []
}
this.stampVersion(true);
}
get changes() {
const changes= [];
for (const field of this.objectHandler.items) {
if (!equal(this.objectHandler.stateObject[field], this.objectHandler.stateObjectSave[field])){
changes.push({
field,
originalState: this.objectHandler.stateObjectSave[field],
currentState: this.objectHandler.stateObject[field]
});
}
}
return changes;
}
get items() {
return this.objectHandler.items;
}
get currentState() {
return this.objectHandler.stateObject;
}
get lastSavedState() {
return this.objectHandler.stateObjectSave;
}
get versionHistory() {
return this.objectHandler.versionHistory;
}
revertToVersion(versionNumber) {
if (this.objectHandler.versionHistory[versionNumber]) {
this.objectHandler.stateObject = {
...this.objectHandler.stateObject,
...this.objectHandler.versionHistory[versionNumber]
}
this.saveAll();
}
}
stampVersion(initial) {
let savedObject = {};
for (const field of this.objectHandler.items) {
savedObject[field] = eot.clone(this.objectHandler.stateObjectSave[field]);
}
this.objectHandler.versionHistory.push(savedObject);
if (this.objectHandler.saveCallBack && (typeof this.objectHandler.saveCallBack === "function") && !initial){
this.objectHandler.saveCallBack(this.objectHandler.stateObjectSave);
}
}
revert(field) {
if (this.objectHandler.items.includes(field)){
this.objectHandler.stateObject[field] = eot.clone(this.objectHandler.stateObjectSave[field]);
}
}
revertAll() {
for (const field of this.objectHandler.items) {
this.revert(field);
}
}
save(field, save = true) {
if (this.objectHandler.items.includes(field)){
this.objectHandler.stateObjectSave[field] = eot.clone(this.objectHandler.stateObject[field]);
}
if (save){
this.stampVersion();
}
}
saveAll() {
for (const field of this.objectHandler.items) {
this.save(field, false);
}
this.stampVersion();
}
}
module.exports = VanillaState;