Skip to content

Instantly share code, notes, and snippets.

@decaylala
Created December 15, 2020 15:15
Show Gist options
  • Save decaylala/f97ec52ca1ffd44e5cd6873696ee6844 to your computer and use it in GitHub Desktop.
Save decaylala/f97ec52ca1ffd44e5cd6873696ee6844 to your computer and use it in GitHub Desktop.

Revisions

  1. decaylala revised this gist Dec 15, 2020. No changes.
  2. decaylala created this gist Dec 15, 2020.
    78 changes: 78 additions & 0 deletions machine.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@

    // Available variables:
    // - Machine
    // - interpret
    // - assign
    // - send
    // - sendParent
    // - spawn
    // - raise
    // - actions
    // - XState (all XState exports)

    const FULL_STOCK = 5;

    const machine = Machine({
    initial: 'normal',
    context: {
    supply: 5
    },
    states: {
    normal: {
    on: {
    "": [
    {
    target: 'empty',
    cond: 'isEmpty',
    },
    {
    target: 'full',
    cond: 'isFull'
    },
    ],
    DISPENSE: {
    target: 'normal',
    actions: 'dispense'
    },
    RESTOCK: {
    target: 'normal',
    actions: 'restock',
    }
    },
    },
    full: {
    on: {
    DISPENSE: {
    target: 'normal',
    actions: 'dispense'
    },
    }
    },
    empty: {
    on: {
    RESTOCK: {
    target: 'normal',
    actions: 'restock'
    }
    }
    }
    }
    }, {
    actions: {
    dispense: assign({
    supply: (context, event) => context.supply - 1
    }),
    restock: assign({
    supply: (context, event) => FULL_STOCK
    })
    },
    guards: {
    isEmpty: (context, event) => {
    return context.supply === 0;
    },
    isFull: (context, event) => {
    return context.supply === FULL_STOCK;
    }
    }
    });