Skip to content

Instantly share code, notes, and snippets.

@rmcfadzean
Last active July 2, 2021 20:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmcfadzean/4790d02ba9b2ccca196312b61ffbba84 to your computer and use it in GitHub Desktop.
Save rmcfadzean/4790d02ba9b2ccca196312b61ffbba84 to your computer and use it in GitHub Desktop.
Playing around with xstate & Copilot
import { createMachine } from 'xstate';
interface Booking {
id: string;
flight: Flight;
paid: boolean;
}
interface Passenger {
name: string;
bookings: Booking[];
}
interface Flight {
from: string;
to: string;
date: Date;
}
// xstate machine for flight bookings
const booking = createMachine<Booking>({
id: 'booking',
initial: 'pending',
context: {
passengers: [],
},
states: {
pending: {
on: {
PENDING: {
target: 'pending',
cond: (c) => c.passengers.length === 0,
},
BOOK: {
actions: assign<Booking>({
id: () => {
const now = new Date();
return `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}-${now.getTime()}`;
},
}),
target: 'booked',
cond: (c) => c.passengers.length > 0,
},
CANCEL: 'cancelled',
},
},
booked: {
on: {
CANCEL: 'pending',
},
},
cancelled: {
on: {
PENDING: 'pending',
},
},
},
});
// xstate machine for passengers
const passenger = createMachine<Passenger>({
id: 'passenger',
initial: 'pending',
context: {
bookings: [],
},
states: {
pending: {
on: {
PENDING: 'pending',
BOOK: {
target: 'booked',
cond: (c) => c.bookings.length === 0,
},
},
},
booked: {
on: {
CANCEL: 'pending',
},
},
},
});
const flight = createMachine<Flight>({
id: 'flight',
initial: 'pending',
context: {
passengers: [],
},
states: {
pending: {
on: {
PENDING: {
target: 'pending',
cond: (c) => c.passengers.length ===
// ran out of characters I guess
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment