Skip to content

Commit 2c72158

Browse files
Merge pull request #3 from Lash-L/optimize_color
Optimize get_color
2 parents 5c936c6 + ac37779 commit 2c72158

File tree

1 file changed

+25
-14
lines changed
  • src/vacuum_map_parser_base/config

1 file changed

+25
-14
lines changed

src/vacuum_map_parser_base/config/color.py

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -117,24 +117,35 @@ def __init__(
117117
self._overriden_room_colors = {}
118118
else:
119119
self._overriden_room_colors = room_colors
120+
self._cached_colors: dict[SupportedColor, Color] = {}
121+
self._cached_room_colors: dict[int, Color] = {}
120122

121123
def get_color(self, color_name: SupportedColor) -> Color:
122-
return self._overriden_colors.get(
123-
color_name,
124-
ColorsPalette.COLORS.get(color_name, ColorsPalette.COLORS.get(SupportedColor.UNKNOWN, (0, 0, 0))),
125-
)
124+
if color_name not in self._cached_colors:
125+
if color_name in self._overriden_colors:
126+
val = self._overriden_colors[color_name]
127+
elif color_name in ColorsPalette.COLORS:
128+
val = ColorsPalette.COLORS[color_name]
129+
elif SupportedColor.UNKNOWN in ColorsPalette.COLORS:
130+
val = ColorsPalette.COLORS[SupportedColor.UNKNOWN]
131+
else:
132+
val = (0,0,0)
133+
self._cached_colors[color_name] = val
134+
return self._cached_colors[color_name]
126135

127136
def get_room_color(self, room_id: str | int) -> Color:
128137
if isinstance(room_id, str):
129138
room_id = int(room_id)
130-
if room_id > len(ColorsPalette.ROOM_COLORS):
131-
room_id = (room_id - 1) % len(ColorsPalette.ROOM_COLORS) + 1
139+
if room_id not in self._cached_room_colors:
140+
if room_id > len(ColorsPalette.ROOM_COLORS):
141+
room_id = (room_id - 1) % len(ColorsPalette.ROOM_COLORS) + 1
132142

133-
key = str(room_id)
134-
return self._overriden_room_colors.get(
135-
key,
136-
ColorsPalette.ROOM_COLORS.get(
137-
key,
138-
ColorsPalette.ROOM_COLORS.get(str(self._random.randint(1, 16)), (0, 0, 0)),
139-
),
140-
)
143+
key = str(room_id)
144+
if key in self._overriden_room_colors:
145+
val = self._overriden_room_colors[key]
146+
elif key in ColorsPalette.ROOM_COLORS:
147+
val = ColorsPalette.ROOM_COLORS[key]
148+
else:
149+
val = ColorsPalette.ROOM_COLORS.get(str(self._random.randint(1, 16)), (0, 0, 0))
150+
self._cached_room_colors[room_id] = val
151+
return self._cached_room_colors[room_id]

0 commit comments

Comments
 (0)