javascript
45 lines · 7 steps
A finite state machine for checkout flow
A lookup table of states and actions drives valid transitions, emitting events on every move.
Explained by
highlit
1const transitions = {
2 cart: { checkout: 'shipping' },
3 shipping: { submitAddress: 'payment', back: 'cart' },
4 payment: { submitPayment: 'review', back: 'shipping' },
5 review: { confirm: 'processing', back: 'payment' },
6 processing: { success: 'complete', failure: 'payment' },
7 complete: {},
8};
9
10class CheckoutMachine extends EventTarget {
11 constructor(state = 'cart', context = {}) {
12 super();
13 this.state = state;
14 this.context = context;
15 }
16
17 can(action) {
18 return action in (transitions[this.state] ?? {});
19 }
20
21 dispatch(action, payload = {}) {
22 const next = transitions[this.state]?.[action];
23 if (!next) {
24 throw new Error(`Invalid action "${action}" from state "${this.state}"`);
25 }
26
27 const from = this.state;
28 this.context = { ...this.context, ...payload };
29 this.state = next;
30
31 this.dispatchEvent(
32 new CustomEvent('transition', {
33 detail: { from, to: next, action, context: this.context },
34 })
35 );
36
37 return this.state;
38 }
39
40 get isTerminal() {
41 return Object.keys(transitions[this.state] ?? {}).length === 0;
42 }
43}
44
45export { CheckoutMachine, transitions };
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Encoding allowed transitions as data keeps the state logic declarative and easy to audit.
- 2Looking up the next state before mutating lets you reject invalid actions cleanly.
- 3Extending EventTarget gives observers a standard way to react to each transition.
Related explainers
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-finite-state-machine-for-checkout-flow-explained-javascript-136d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.