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. 😍
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.
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 😛
First, you create a regex that matches
@ followed by a series of word symbols.
Then you create a generator that runs this regex in a loop. Each
UserRegex.exec() returns the next 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
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.
["@swizec", "swizec"]["@kyleshevlin", "kyleshevlin"]["@lukeed05", "lukeed05"]
Here's a CodeSandbox you can play with
Here's how it works 👇
Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️