0.0.3 β€’ Published 1 year ago

@bemedev/x-matches v0.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Better way to macth states in XState

Short introduction to Xstate

XState is a implementation of Statecharts, a graphical way to represent complexity in code. Every you need to know is inside the docs.

Problems

  • Orthogonal/parallel state

To matches a parallel state, you need to put as parameter an entire object. Generally, you only need to know if the state is inside a child or a grandchild of the current state. XState is recursive, so for a small check, you can write a deep recursive object as parameter with infinite nested children.

  • Compound state

It’s the same problem as orthogonal but with less complexity. Here, I want to emphasize the problem of nested objects. Sometimes you only need to know if the state is inside the parent and you don’t care about the children. But in the current configuration of state.matches, you need to put as parameter and the nested current children.

  • Direct implementation polyfill for core XState

Not yet implemented

The solution

A function to match with string representation of the current state or parent, or grandparent πŸ˜ŒπŸ˜΅β€πŸ’«, or… You see where I want to go!

I listed the cases inside this code block :

import buildMatches from '@bemedev/x-matches';

// Case 1 -> simple state
const simpleMatch = buildMatches('idle');

// Case 2 -> compound state
const compoundMatch = buildMatches({
  fetching: {
    parent: 'child',
  },
});

// Case 3 -> parallel state
const parallelMatch = buildMatches({
  auth: {
    /* ... */
  },
  fetching: {
    /* ... */
  },
});

// The resulting function accepts a param array :
parallelMacth('auth', 'fetching');
compoundMatch('fetching', 'fetching.parent', 'fetching.parent.child');

Add-ons

We add possibilities to do logical "or" and logical "and"

Code example:

import buildMatches from '@bemedev/x-matches';

// Case 3 -> parallel state
const matches = buildMatches({
  auth: 'notAuthenticated',
  fetching: {
    cache: 'nodata',
    backend: 'data',
  },
});

matches({ or: ['auth', 'fetching.cache.data'] }); // => true

matches({
  and: ['auth.notAuthenticated', 'fetching.cache.data'],
}); // => false

matches(
  {
    and: ['auth.notAuthenticated', 'fetching.cache.data'],
  },
  'auth',
); // => false

matches(
  {
    or: ['auth', 'fetching.cache.data'],
  },
  'fetching',
); // => true

matches({
  and: [
    {
      or: ['auth', 'fetching.cache.data'],
    },
    'fetching',
  ],
}); // => true

NB : The param array acts like a logical "and"

Live documentation here

Enjoy your function ✌🏾😎 !