惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Implementing a simple state machine library in JavaScript
2020-01-20 · via Kent C. Dodds Blog

Watch "Implement a simple Finite State Machine library in JavaScript" on egghead.io

If you're like me, the first time you heard the words "state machine" you were a little intrigued and as you dove in deeper, you were more confused than when you started. I find that when I hit that situation, writing my own implementation of the concept helps solidify the concept for me. So that's what we're going to do together.

I'm not going to take time to try and explain state machines or their use cases, so you'll need to find other resources for that. Here I'm just going to go through what a simple state machine implementation might look like. I wouldn't recommend using this implementation in production. For that, check out xstate.

There's a brilliant website (statecharts.github.io by Erik Mogensen) where you can learn a lot about this concept called "State Charts." (A state chart is basically a state machine with a few additional characteristics and it's another thing I'd recommend learning about.) On that website, there's a page titled What is a state machine? where you can learn the fundamentals of what a state machine is and that's where we're going to gather the parameters (or requirements) for our own state machine implementation. Here are some of those (borrowed from the site):

  • One state is defined as the initial state. When a machine starts to execute, it automatically enters this state.
  • Each state can define actions that occur when a machine enters or exits that state. Actions will typically have side effects.
  • Each state can define events that trigger a transition.
  • A transition defines how a machine would react to the event, by exiting one state and entering another state.
  • A transition can define actions that occur when the transition happens. Actions will typically have side effects.

Also, "When an event happens:"

  • The event is checked against the current state's transitions.
  • If a transition matches the event, that transition “happens”.
  • By virtue of a transition “happening”, states are exited, and entered and the relevant actions are performed
  • The machine immediately is in the new state, ready to process the next event.

Ok, so let's get started. Let's start with something simple. A toggle! Here's our initial code:

function createMachine(stateMachineDefinition) {
	const machine = {
		// machine object
	}
	return machine
}

// here's how we'll create the state machine
const machine = createMachine({
	// state machine definition object here...
})

// here's how we use the state machine
// comments are what we _want_ to have logged
let state = machine.value
console.log(`current state: ${state}`) // current state: off

state = machine.transition(state, 'switch')
console.log(`current state: ${state}`) // current state: on

state = machine.transition(state, 'switch')
console.log(`current state: ${state}`) // current state: off

The state machine definition object

We'll start by filling out our state machine definition object and then we can figure out how to make the state machine do what we want it to with that information (ADD: API Driven Development).

One state is defined as the initial state. When a machine starts to execute, it automatically enters this state.

Simple enough, we'll have the user provide us with what that initialState value should be:

const machine = createMachine({
	initialState: 'off',
})

And we'll probably want to have a definition for our states as well:

const machine = createMachine({
	initialState: 'off',
	off: {},
	on: {},
})

Ok, great. Onto the next:

Each state can define actions that occur when a machine enters or exits that state. Actions will typically have side effects.

So we need to allow the user to provide a function that will be called when on enter and on exit for a given state:

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {},
			onExit() {},
		},
	},
	on: {
		actions: {
			onEnter() {},
			onExit() {},
		},
	},
})

And we'll add console.logs so we can check our work later.

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
	},
})

Ok, so now what's next?

Each state can define events that trigger a transition.

Alrighty, let's add a transitions property to our state definitions:

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
		transitions: {},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
		transitions: {},
	},
})

The off state should be able to transition to the on state and we'll call that event "switch". Then the on state should be able to transition to the off state as well and it makes sense to call that "switch" as well, so let's add a switch property to our transitions object:

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
		transitions: {
			switch: {},
		},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
		transitions: {
			switch: {},
		},
	},
})

Sweet. And the next one:

A transition defines how a machine would react to the event, by exiting one state and entering another state.

Ok, so I think that we can specify a target for our transition event and when that event comes around, our machine will transition us from the current state to the target state:

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'on',
			},
		},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'off',
			},
		},
	},
})

Cool, so when our state machine is in the off state and we call machine.transition(state, 'switch') then it should transition from the off state to the on state. We'll implement that logic when we get to it, but so far our definition has everything we need for that to happen.

Alright, let's check out the last one for the definition:

A transition can define actions that occur when the transition happens. Actions will typically have side effects.

Based on that, our state enter/exit can have actions, and our transitions can have actions too. At first when I read this, I was confused because it felt like two ways to do the same thing, but if you remember that in more real-world state machines, there can be many ways to enter a state and maybe we want some side-effect to happen only when transitioning to state A from a specific state B but not from state C. So let's add an action to our transition objects (and we'll put a console.log in there to keep track of it later).

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'on',
				action() {
					console.log('transition action for "switch" in "off" state')
				},
			},
		},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'off',
				action() {
					console.log('transition action for "switch" in "on" state')
				},
			},
		},
	},
})

Excellent. We've fleshed out the API for the state definition object. Now let's implement what happens when transition is called.

Handling transitions

When a user wants to create a machine, we've already specified this as the API:

const machine = createMachine({
	// state machine definition object
})

machine.value // current state
machine.transition(currentState, eventName)

Technically, we could make our state machine default the current state to machine.value, but I like the idea of transition accepting the current state from the user (and this is what xstate does) so that's what we'll go with.

So here's what we need for our initial implementation of createMachine:

function createMachine(stateMachineDefinition) {
	const machine = {
		// machine object
	}
	return machine
}

Let's go ahead and add the value and transition properties:

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			return machine.value
		},
	}
	return machine
}

Remember, currentState would be something like 'off' or 'on' in our case and event would be 'switch' for our toggle example.

Great, now let's go down the list and implement things one by one:

The event is checked against the current state's transitions.

Alright, let's grab the transitions object and determine the destination transition.

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			const currentStateDefinition = stateMachineDefinition[currentState]
			const destinationTransition = currentStateDefinition.transitions[event]

			return machine.value
		},
	}
	return machine
}

To be clear, the destinationTransition at this point for our off -> on transition would be:

{
  target: 'on',
  action() {
    console.log('transition action for "switch" in "off" state')
  },
}

So here we've successfully accessed the transition information for this currentState + event combo.

If a transition matches the event, that transition “happens”.

Ok, so if the user defined a transition from the current state with this event, then we'll continue, otherwise, we'll exit early:

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			const currentStateDefinition = stateMachineDefinition[currentState]
			const destinationTransition = currentStateDefinition.transitions[event]
			if (!destinationTransition) {
				return
			}

			return machine.value
		},
	}
	return machine
}

By virtue of a transition “happening”, states are exited, and entered and the relevant actions are performed

Ok, so we'll need to call the action for the transition, the onExit for the current state and the onEnter for the next state. To do that, we'll also need to get the destination state definition as well. Let's do all of that:

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			const currentStateDefinition = stateMachineDefinition[currentState]
			const destinationTransition = currentStateDefinition.transitions[event]
			if (!destinationTransition) {
				return
			}
			const destinationState = destinationTransition.target
			const destinationStateDefinition =
				stateMachineDefinition[destinationState]

			destinationTransition.action()
			currentStateDefinition.actions.onExit()
			destinationStateDefinition.actions.onEnter()

			return machine.value
		},
	}
	return machine
}

And finally:

The machine immediately is in the new state, ready to process the next event.

We've got to update the machine's value which is the target for the transition (which we've assigned to the destinationState variable):

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			const currentStateDefinition = stateMachineDefinition[currentState]
			const destinationTransition = currentStateDefinition.transitions[event]
			if (!destinationTransition) {
				return
			}
			const destinationState = destinationTransition.target
			const destinationStateDefinition =
				stateMachineDefinition[destinationState]

			destinationTransition.action()
			currentStateDefinition.actions.onExit()
			destinationStateDefinition.actions.onEnter()

			machine.value = destinationState

			return machine.value
		},
	}
	return machine
}

All together

Alright, so here's the whole thing:

function createMachine(stateMachineDefinition) {
	const machine = {
		value: stateMachineDefinition.initialState,
		transition(currentState, event) {
			const currentStateDefinition = stateMachineDefinition[currentState]
			const destinationTransition = currentStateDefinition.transitions[event]
			if (!destinationTransition) {
				return
			}
			const destinationState = destinationTransition.target
			const destinationStateDefinition =
				stateMachineDefinition[destinationState]

			destinationTransition.action()
			currentStateDefinition.actions.onExit()
			destinationStateDefinition.actions.onEnter()

			machine.value = destinationState

			return machine.value
		},
	}
	return machine
}

const machine = createMachine({
	initialState: 'off',
	off: {
		actions: {
			onEnter() {
				console.log('off: onEnter')
			},
			onExit() {
				console.log('off: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'on',
				action() {
					console.log('transition action for "switch" in "off" state')
				},
			},
		},
	},
	on: {
		actions: {
			onEnter() {
				console.log('on: onEnter')
			},
			onExit() {
				console.log('on: onExit')
			},
		},
		transitions: {
			switch: {
				target: 'off',
				action() {
					console.log('transition action for "switch" in "on" state')
				},
			},
		},
	},
})

let state = machine.value
console.log(`current state: ${state}`)
state = machine.transition(state, 'switch')
console.log(`current state: ${state}`)
state = machine.transition(state, 'switch')
console.log(`current state: ${state}`)

And if you were to pop that up in your Chrome DevTools, here are the logs you'd get:

current state: off
transition action for "switch" in "off" state
off: onExit
on: onEnter
current state: on
transition action for "switch" in "on" state
on: onExit
off: onEnter
current state: off

And you can play around with this in codesandbox.

I hope you found that interesting, informative, and entertaining. If you're really like to dive into this stuff further, then definitely give statecharts.github.io a look and give David Khourshid a follow. He's on a personal mission to make state machines more approachable and is responsible for my own interest in the concept.

Good luck!