godot-xterm/addons/gut/one_to_many.gd

44 lines
1.1 KiB
GDScript
Raw Normal View History

# ------------------------------------------------------------------------------
# This datastructure represents a simple one-to-many relationship. It manages
# a dictionary of value/array pairs. It ignores duplicates of both the "one"
# and the "many".
# ------------------------------------------------------------------------------
var _items = {}
2023-01-20 23:34:39 +01:00
# return the size of _items or the size of an element in _items if "one" was
# specified.
2023-01-20 23:34:39 +01:00
func size(one = null):
var to_return = 0
2023-01-20 23:34:39 +01:00
if one == null:
to_return = _items.size()
2023-01-20 23:34:39 +01:00
elif _items.has(one):
to_return = _items[one].size()
return to_return
2023-01-20 23:34:39 +01:00
# Add an element to "one" if it does not already exist
func add(one, many_item):
2023-01-20 23:34:39 +01:00
if _items.has(one) and !_items[one].has(many_item):
_items[one].append(many_item)
else:
_items[one] = [many_item]
2023-01-20 23:34:39 +01:00
func clear():
_items.clear()
2023-01-20 23:34:39 +01:00
func has(one, many_item):
var to_return = false
2023-01-20 23:34:39 +01:00
if _items.has(one):
to_return = _items[one].has(many_item)
return to_return
2023-01-20 23:34:39 +01:00
func to_s():
2023-01-20 23:34:39 +01:00
var to_return = ""
for key in _items:
to_return += str(key, ": ", _items[key], "\n")
return to_return