-
Notifications
You must be signed in to change notification settings - Fork 9
/
state.lua
70 lines (58 loc) · 1.39 KB
/
state.lua
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
local json = require "cjson"
local State = {}
function State:new(collectHistory)
local obj = {
state = {},
timestamp = 0,
valid = true,
history = collectHistory and {} or nil
};
setmetatable(obj, self)
self.__index = self
return obj
end
function State:getState()
local list = {}
for key, value in pairs(self.state) do
local clone = json.decode(key)['value']
for i = 1, value do
table.insert(list, clone)
end
end
return list
end
function State:getHistory()
return self.history
end
function State:validate(timestamp)
if not self.valid then
error("Invalid state.")
elseif tonumber(timestamp) < self.timestamp then
print("Invalid timestamp.")
self.valid = false
error(string.format("Update with timestamp (%d) is lower than the last timestamp (%d). Invalid state.", timestamp, self.timestamp))
end
end
function State:process(update)
local value = json.encode({ value = update.value })
local count = self.state[value] or 0
count = count + update.diff
if count <= 0 then
self.state[value] = nil
else
self.state[value] = count
end
if self.history then
table.insert(self.history, update)
end
end
function State:update(updates, timestamp)
if #updates > 0 then
self:validate(timestamp)
self.timestamp = timestamp
for _, update in ipairs(updates) do
self:process(update)
end
end
end
return State