JavaScript generators are amazing. A brilliant concept infinitely useful on paper.
They let you write infinite loops that terminate. Yield values from functions before they finish. Build lazy data structures. Lazy evaluation programming!
A functional programmer's wet dream. 😍
And I bet you've never used a JavaScript generator even once did you? Do you even know the syntax?
I bet you don't.
Turns out generators aren't very useful in practice. 😢
But yesterday, after years of knowing about generators, years of itching to use them, years of ... I FOUND A USE! A real world practical use-case where generators actually make your code better. 😱
We were adding automatic linking of twitter usernames to my TechLetterApp project. Find a piece of text, parse out @username
instances, turn into links.
Easy right?
I thought so too. Complications around inserting complex nodes into an abstract syntax tree (AST) aside, parsing those usernames is hard to do elegantly.
Unless you use generators 😛
Curated JavaScript Essays
Get a series of curated essays on JavaScript. Lessons and insights from building software for production. No bullshit.
Here's how we did it 👇
First, you create a regex that matches @
followed by a series of word symbols.
const UserRegex = new RegExp(/@(\w+)/, "g")
Then you create a generator that runs this regex in a loop. Each UserRegex.exec()
returns the next match.
function* getUsernames(string) {
let match = null;
do {
match = UserRegex.exec(string);
if (match) {
yield match;
}
} while (match);
}
We have a *getUsernames
generator that takes a string
. The asterisk notation changes a function to a generator.
Inside, a loop runs as long as match
has a value. Assigned on each iteration as a UserRegex.exec
call.
We yield
existing values on every loop iteration. Last one will be null
and we don't want to return those.
Yield is how you return values from generators. Notice that even after returning a value, the generator keeps running. That's the generator magic 🧙♀️
You can now find all usernames in a string with a loop.
const string = "this is a test with @swizec and @kyleshevlin, maybe @lukeed05"
for (const username of getUsernames(string)) {
console.log(username)
}
That outputs
["@swizec", "swizec"] ["@kyleshevlin", "kyleshevlin"] ["@lukeed05", "lukeed05"]
Here's a CodeSandbox you can play with
Cheers, ~Swizec
Continue reading about Finally, a practical use case for JavaScript generators!
Semantically similar articles hand-picked by GPT-4
- Advent of Code Day 15 – Dueling JavaScript Generators
- Livecoding Recap 48: JavaScript async/await and Morty's Mindblowers
- Async, await, catch – error handling that won't drive you crazy
- Livecoding Recap 48- Why contributing to big opensource projects is still hard
- Custom markdown extensions with Remark and HAST handlers
Want to become a JavaScript expert?
Learning from tutorials is great! You follow some steps, learn a smol lesson, and feel like you got this. Then you go into an interview, get a question from the boss, or encounter a new situation and o-oh.
Shit, how does this work again? 😅
That's the problem with tutorials. They're not how the world works. Real software is a mess. A best-effort pile of duct tape and chewing gum. You need deep understanding, not recipes.
Leave your email and get the JavaScript Essays series - a series of curated essays and experiments on modern JavaScript. Lessons learned from practice building production software.
Curated JavaScript Essays
Get a series of curated essays on JavaScript. Lessons and insights from building software for production. No bullshit.
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️