☯️ Classifier Class
☯️ Classifier Class — A Rich Map
Overview
Classifier is a hierarchical, prefix-based multimap where keys are sequences and values are stored in equivalence classes determined by those key-sequences.
- Behaves like a generalized
Mapwhere keys are iterable sequences. - Supports multiple values per key-sequence.
- Implements a sorted trie for efficient prefix queries.
- Values at each node form an equivalence class, optionally sorted.
Node Structure
Each node contains:
parent— parent node (null for root)key— key associated with this node (undefined for root)depth— depth in the tree (root = 0)sortedKeys— aSortedArrayof child keyskeyToChild— aMapfrom key → child nodenin— number of sequences ending exactly at this nodenout— number of sequences ending strictly below this nodeclass— a collection of items forming the equivalence class at this nodesorter(node)— returns[keyComparator, itemComparator?]to define order
Constructor
new Classifier(sorter, parent, key)
sorter— function receiving the node and returning[keyComparator, itemComparator?].parent— parent node,nullfor root.key— key leading from parent to this node,undefinedfor root.
Collection Interface
n()
Returns total number of item occurrences in the subtree (nin + nout).
has(keys)
Checks if a key sequence exists and ends at a terminating node.
add(keys, item, xTimes=1)
Adds an item to a sequence of keys. Creates nodes if necessary.
remove(keys, xTimes=Infinity)
Removes occurrences of a stored sequence, up to xTimes. Prunes this node if becomes empty.
clear()
Removes all entries in this node and subtree, clearing .class and children. Prunes this node.
get(query, first=true)
Returns all items matching a key prefix (supports undefined as wildcard).
Queue Interface
reverse()
Returns all items in the classifier in reverse traversal order.
peek(first=true)
Returns the first or last item in the subtree without removing it.
poll(first=true)
Returns and removes the first or last item in the subtree.
Traversal Methods
path()
Returns a Path<Classifier> from the root to this node.
with(path)
Returns the descendant Classifier addressed by the given path (iterable) of keys.
descendants(query=[], first=true)
Depth-first traversal of nodes, optionally filtered by prefix query.
query— optional array of keys;undefinedis a wildcard.first— traversal order, true = ascending.
*keys()
Yields all stored key sequences in the classifier.
*values()
Yields all stored items in traversal order.
*entries()
Yields [keys, item] pairs for all stored items.
Example Usage
const clf = new Classifier();
clf.add(['a','b','c'], 'abc');
// Prefix query
for (const item of clf.get([undefined,'b'])) {
console.log(item); // all items where repr[1] === 'b'
}
Comments
Post a Comment