npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fn-machine

v0.1.2

Published

a tiny functional state machine

Downloads

1,617

Readme

fn-machine

A tiny, functional, state machine utility

install

npm install --save fn-machine

usage

fn-machine consists of 3 functions. The first two are used to define a machine:

machine([State], 'initialState', initialContextObj, stateChangeCallback, loggerFn)

state('name', transitionsObj, enterFunction, exitFunction)

The third function is what would traditionally be called a send() function. This function is returned by calling machine(...).

Setting up a machine


// import the setup functions
import {machine, state} from 'fn-machine';

// initial context object
const initialContext = {
  loading: false,
  users: [],
};

function loadUsers() {
  // simulate a network request
  setTimeout(() => {
    // once the request completes, we can call `myMachine` (the 'send' function).
    myMachine('loaded', {users:['foo', 'bar']})
  }, 1000);
};

// initialize a machine
const myMachine = machine([
  state('initial', {
    // each method on this object represents a transition for this particular state.
    loadData: (detail, context) => {
      // a transition should return the new state, as well as the optional context.
      // here we return {state:'loadingData'} to signify we want the state to now be 'loadingData'.
      return {
        state:'loadingData',
      }
    }
  }),
  state('loadingData', {
    loaded: (detail, context) => {
      return {
        state: 'loadedData',
        context: {...context, ...detail, ...{loading: false}}
      }
    }
  }, context => {// call loadUsers when this state is entered, and return the new context.
    loadUsers();
    return {...context, ...{loading: true}};
  }),
  state('loadedData', {}) // 'loadedData' is an empty/final state. There are no transitions.
], 'initial', initialContext, newState => {
  console.log('myMachine state changed:', newState.state, newState.context);
}, console.log);// pass an optional logger function

In the loadUsers() function above, we invoke the third function provided by fn-machine, which is the send function. The send function takes a string as the first parameter, which is the name of a transition we'd like to invoke, and optionally a detail object, which contains some data we want the machine to work with, and/or update the context with.

You can also define transitions using a short-hand syntax like so:

state('myState', {
  someAction: 'newState',
});

which is equivelent to:

state('myState', {
  someAction: (detail, context) => {
    return {
      state: 'newState',
      context: {...context, ...detail},
    };
  },
});

More examples

There is an example in this repo, or you can play around with this codepen that shows a basic integration with LitElement.

mermaid

There are two utility functions to convert to and from mermaid syntax.

toMermaid([state('on', {powerOff: 'off'}, state('off', {powerOn: 'on'}))], 'off');

produces a string like that you can process with mermaidjs to visualize your machine:

stateDiagram-v2
[*] --> off
on --> off: powerOff
off --> on: powerOn

Or, you can take a mermaid string and output some stub javascript:

const mermaidStr = `
stateDiagram-v2
[*] --> off
on --> off: powerOff
off --> on: powerOn
`;
fromMermaid(mermaidStr);

which produces:

[state('on', {powerOff: 'off'}, state('off', {powerOn: 'on'}))]

These are useful for visualization and initial creation of your machines, but beware that if your machine transitions contain logic, that logic would be lost should you try to go full circle: machine -> mermaid -> machine.

Contributing

Yes! PR's are welcome. Tests are written in mocha. Run with npm run test or yarn test. Typechecking is provided by typescript via JSDoc annotations.