Friend, you don't often get to show off your leetcode skills at work. They get you through the whiteboard interview and vanish forever.
Yesterday I ran into a rare challenge that let me use those skills. Thought I'd share ✌️
You've got this string of buggy JSX.
JSX confused an HTML parser–stringifier and this is what happened. You can't put it back through a parser because now it's neither valid HTML nor valid JSX. 😅
Here's the data model – part of an abstract syntax tree – that produces the above result:
And here's the output you want:
The tools to stringify your AST exist 👉 toHTML(tree)
But you need to:
- avoid quotes around JSX props denoted by
{}
- avoid breaking JSX object props denoted by
{{ }}
Looks like the parser takes every space as a new attribute. The stringifier wraps every attribute in quotes.
Have fun ❤️
Here's a codesandbox I prepared, if you want to play around.
Give it a shot before you read on, at least a little think.
Did you finish the challenge? Had fun?
I did :P
You can solve this challenge in 2 parts.
- fix quotes around JSX props denoted by
{}
- fix JSX object props denoted by
{{ }}
Each issue falls on a different level of computational solvability. That's a bad phrasing for a 2 semester class I took in college.
In computer science you have automata theory. It teaches you the classes of approaches that can solve different classes of computational problems.
The other side of this coin are languages. Regular languages, context-free languages, context-sensitive languages. It goes on.
Math gibberish for:
- you can use finite state machines to parse regular languages
- you can't for context-sensitive languages
Easiest way to know which you're facing 👉 if you have to match open/close parentheses, you're dealing with context.
Fix quotes around {}
You can solve the first part by summoning Cthulhu.
Here's the bit that summons Cthulhu and solves our problem:
This code uses regex to fix HTML even though HTML is not a regular language and is therefore not parseable by regex.
Why does it work then? 🤨
It works because it doesn't rely on matching open/close tags. Looks like it does, but it doesn't.
This part here /\<(.+\w+)="\{(.*)\}"(.*)\>/
asks for: "Give me any pair of "{ }"
, matched or not, that appears between any pair of <>
, matched or not
The regex returns 3 matched groups:
- everything before the pair
- everything inside the pair
- everything after the pair
We use those groups to replace with a fixed string:
Open <
, first group, ={
, second group, }
, third group, close >
. Then repeat in a loop until no more candidates are found.
Matching never matters and that's why this works.
Fix broken {{ }}
props
The broken object props are harder. Here you are dealing with a contextual language – you have to match the open {{
to its nearest closing }}
.
If you don't, you'll get the wrong result.
That means you have to solve this one before stringification. When you still have access to the underlying AST.
My idea was to iterate through the props and collect them into a new object. When you hit {{
, start collecting values into a new prop, add to new object as full prop when you hit }}
.
Here's how:
This code sets up a method that recursively visits all children in a tree. Makes it useful in a more general case.
Start the algorithm if you encounter an element with {{
in its properties.
Prep a value for new props, a flag that says when you're collecting, and 2 variables to collect into.
Then you iterate and:
- if
{{
is encountered, start collecting - if you're collecting, add values to the current prop
- if
}}
is encountered, stop collecting and create a new prop - push unchanged prop to new object normally
Final Object.fromEntries
call takes the generated array of [key, value]
pairs and turns them into a properties object.
Upon stringification, this gets wrapped in "
quotes, but the Cthulhu summoning code fixes that.
And you get the correct result. Here's a codesandbox for proof
And you thought computer science was useless in web development. Ha!
Cheers,
~Swizec
Continue reading about You though computer science has no place in webdev? Here's a fun coding challenge
Semantically similar articles hand-picked by GPT-4
- How to debug unified, rehype, or remark and fix bugs in markdown processing
- How to debug unified, rehype, or remark and fix bugs in markdown processing
- Hacking the React AST for fun and profit – #CodeWithSwiz ep34
- LOLCODE-to-JavaScript compiler babel macro
- Sometimes your worst code is your best code
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below 👇
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open 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. 👌"
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 ❤️