All files / xstate/examples/src dieHardMachine.js

0% Statements 0/13
100% Branches 0/0
0% Functions 0/4
0% Lines 0/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                                                                                                                                                                           
const { Machine, actions } = require('xstate');
const { assign } = actions;
const {
  getShortestValuePaths,
  deserializeStateString
} = require('xstate/lib/graph');
 
const dieHardMachine = Machine(
  {
    initial: 'pending',
    states: {
      pending: {
        on: {
          '': {
            target: 'success',
            cond: 'weHave4Gallons'
          },
          POUR_3_TO_5: {
            actions: 'pour3to5'
          },
          POUR_5_TO_3: {
            actions: 'pour5to3'
          },
          FILL_3: {
            actions: 'fill3'
          },
          FILL_5: {
            actions: 'fill5'
          },
          EMPTY_3: {
            actions: 'empty3'
          },
          EMPTY_5: {
            actions: 'empty5'
          }
        }
      },
      success: {}
    }
  },
  {
    actions: {
      pour3to5: assign((ctx, e) => {
        const poured = Math.min(5 - ctx[5], ctx[3]);
 
        return {
          3: ctx[3] - poured,
          5: ctx[5] + poured
        };
      }),
      pour5to3: assign((ctx, e) => {
        const poured = Math.min(3 - ctx[3], ctx[5]);
 
        return {
          3: ctx[3] + poured,
          5: ctx[5] - poured
        };
      }),
      fill3: assign({ 3: 3 }),
      fill5: assign({ 5: 5 }),
      empty3: assign({ 3: 0 }),
      empty5: assign({ 5: 0 })
    },
    guards: {
      weHave4Gallons: ctx => ctx[5] === 4
    }
  },
  { 3: 0, 5: 0 }
);
 
const shortestValuePaths = getShortestValuePaths(dieHardMachine, {
  events: {
    POUR_3_TO_5: [{ type: 'POUR_3_TO_5' }],
    POUR_5_TO_3: [{ type: 'POUR_5_TO_3' }],
    FILL_3: [{ type: 'FILL_3' }],
    FILL_5: [{ type: 'FILL_5' }],
    EMPTY_3: [{ type: 'EMPTY_3' }],
    EMPTY_5: [{ type: 'EMPTY_5' }]
  }
});
 
Object.keys(shortestValuePaths).forEach(key => {
  const state = deserializeStateString(key);
  console.log(state, shortestValuePaths[key]);
});