Skip to content
Swizec Teller - a geek with a hatswizec.com

You though computer science has no place in webdev? Here's a fun coding challenge

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.

Click through for source
Click through for source

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:

Click through for source
Click through for source

And here's the output you want:

Click through for source
Click through for source

The tools to stringify your AST exist 👉 toHTML(tree)

But you need to:

  1. avoid quotes around JSX props denoted by {}
  2. 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.

Click through for source
Click through for source

Give it a shot before you read on, at least a little think.


Did you finish the challenge? Had fun?

I did :P

XKCD Nerd Sniping
XKCD Nerd Sniping

You can solve this challenge in 2 parts.

  1. fix quotes around JSX props denoted by {}
  2. 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.

rysvgpngjj594d

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.

Click through for source

Here's the bit that summons Cthulhu and solves our problem:

Click through for source
Click through for source

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:

  1. everything before the pair
  2. everything inside the pair
  3. everything after the pair

We use those groups to replace with a fixed string:

Click through for source
Click through for source

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.

magic giphy

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:

Click through for source
Click through for source

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.

Click through for source
Click through for source

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

Click through for source
Click through for source

And you thought computer science was useless in web development. Ha!

Cheers,
~Swizec

Did you enjoy this article?

Published on August 21st, 2020 in Computer Science, Front End, Technical

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

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. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

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 ❤️