79 lines
2.5 KiB
JavaScript
79 lines
2.5 KiB
JavaScript
var ex = this
|
||
ex[prosperon.DOC] = `
|
||
A set of utilities for iterating over a hierarchy of actor-like objects, as well
|
||
as managing tag-based lookups. Objects are assumed to have a "objects" property,
|
||
pointing to children or sub-objects, forming a tree.
|
||
`
|
||
|
||
function eachobj(obj, fn) {
|
||
var val = fn(obj)
|
||
if (val) return val
|
||
for (var o in obj.objects) {
|
||
if (obj.objects[o] === obj) console.error(`Object ${obj.toString()} is referenced by itself.`)
|
||
val = eachobj(obj.objects[o], fn)
|
||
if (val) return val
|
||
}
|
||
}
|
||
|
||
ex.all_objects = function (fn, startobj = world) {
|
||
return eachobj(startobj, fn)
|
||
}
|
||
ex.all_objects[prosperon.DOC] = `
|
||
:param fn: A callback function that receives each object. If it returns a truthy value, iteration stops and that value is returned.
|
||
:param startobj: The root object at which iteration begins, default is the global "world".
|
||
:return: The first truthy value returned by fn, or undefined if none.
|
||
Iterate over each object (and its sub-objects) in the hierarchy, calling fn for each one.
|
||
`
|
||
|
||
ex.find_object = function (fn, startobj = world) {}
|
||
ex.find_object[prosperon.DOC] = `
|
||
:param fn: A callback or criteria to locate a particular object.
|
||
:param startobj: The root object at which search begins, default "world".
|
||
:return: Not yet implemented.
|
||
Intended to find a matching object within the hierarchy.
|
||
`
|
||
|
||
var gtags = {}
|
||
|
||
ex.tag_add = function (tag, obj) {
|
||
gtags[tag] ??= new Set()
|
||
gtags[tag].add(obj)
|
||
}
|
||
ex.tag_add[prosperon.DOC] = `
|
||
:param tag: A string tag to associate with the object.
|
||
:param obj: The object to add under this tag.
|
||
:return: None
|
||
Associate the given object with the specified tag. Creates a new tag set if it does not exist.
|
||
`
|
||
|
||
ex.tag_rm = function (tag, obj) {
|
||
delete gtags[tag].delete(obj)
|
||
}
|
||
ex.tag_rm[prosperon.DOC] = `
|
||
:param tag: The tag to remove the object from.
|
||
:param obj: The object to remove from the tag set.
|
||
:return: None
|
||
Remove the given object from the specified tag’s set, if it exists.
|
||
`
|
||
|
||
ex.tag_clear_guid = function (obj) {
|
||
for (var tag in gtags) gtags[tag].delete(obj)
|
||
}
|
||
ex.tag_clear_guid[prosperon.DOC] = `
|
||
:param obj: The object whose tags should be cleared.
|
||
:return: None
|
||
Remove the object from all tag sets.
|
||
`
|
||
|
||
ex.objects_with_tag = function (tag) {
|
||
if (!gtags[tag]) return []
|
||
return Array.from(gtags[tag])
|
||
}
|
||
ex.objects_with_tag[prosperon.DOC] = `
|
||
:param tag: A string tag to look up.
|
||
:return: An array of objects associated with the given tag.
|
||
Retrieve all objects currently tagged with the specified tag.
|
||
`
|
||
|
||
return ex
|