objectify

master
Bel LaPointe 2022-09-20 15:29:48 -06:00
parent 8a9cb5a82d
commit ac7b583f76
1 changed files with 14 additions and 2 deletions

View File

@ -7,10 +7,11 @@ class Writer:
def __init__(self, writer):
self.writer = writer
self.previous = Line([])
self.chooser = LineChooserLatestSticky()
def write(self, v):
latest = Line(v)
chosen = Line.choose(self.previous, latest)
chosen = self.chooser.choose(self.previous, latest)
if chosen.v != self.previous.v:
self.writer.write(chosen)
self.previous = chosen
@ -73,13 +74,24 @@ class Line:
def __str__(self):
return json.dumps({"t":self.t, "v": self.v})
def is_nothing(self):
return not self.v
def is_recent(self):
return time.time() - self.t < 1
class LineChooser:
def choose(a, b):
if not a:
return b
if not b:
return a
return self._choose(a, b)
class LineChooserLatestSticky(LineChooser):
def _choose(self, a, b):
latest = max([a,b], key=lambda x:x.t)
oldest = min([a,b], key=lambda x:x.t)
if not latest.v and time.time() - oldest.t < 1:
if latest.is_nothing() and oldest.is_recent():
return oldest
return latest