Matches

Overview

matches(...) is used to check if a given state node matches a specified path. It's particularly useful for determining the current state of a state machine or checking if a specific sub-state is active.

Syntax

function matches(state: StateNode, path: string): boolean;

Parameters

  • state (StateNode): The current state node to check against.

  • path (string): A dot-separated string representing the path to match.

Return Value

Returns true if the state matches the given path, false otherwise.

Description

The matches(...) function performs a recursive check to determine if the given state matches the specified path . It works as follows:

  1. If the state's name exactly matches the path, it returns true .

  2. If the path starts with the state's name followed by a dot, it checks the active children of the state.

  3. For each active child, it recursively calls matches with the remaining part of the path.

  4. If any active child matches, it returns true .

  5. If no match is found, it returns false .

Examples

import { atomic, compound, emitEvent, matches, resolveState } from 'hine';
// Define a toggle state machine
const toggleConfig = compound('toggle', {
initial: 'inactive',
children: [
atomic('inactive', {
on: { toggle: 'active' },
}),
atomic('active', {
on: { toggle: 'inactive' },
}),
],
});
// Create an instance of the state machine
const myToggle = resolveState(toggleConfig);
// Check initial state
console.log(matches(myToggle, 'toggle.inactive')); // true
console.log(matches(myToggle, 'toggle.active')); // false
// Emit an event to change state
emitEvent(myToggle, 'toggle');
// Check new state
console.log(matches(myToggle, 'toggle.inactive')); // false
console.log(matches(myToggle, 'toggle.active')); // true

Notes

  • The path string should use dot notation to represent nested states (e.g., 'parent.child.grandchild' ).

  • Be careful about using state names with a dot ( '.' ) in them. This may lead to false-positives.

    const stateConfig = compound('parent', {
    initial: 'child.with.dots',
    children: [atomic('child.with.dots'), atomic('other.child')],
    });
    const state = resolveState(stateConfig);
    console.log(matches(state, 'parent.child.with.dots')); // true (correct)
    console.log(matches(state, 'parent.child')); // true (false positive!)