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

    ~ Ashish Kumar

    Join 15,883+ engineers learning lessons from my "raw and honest from the heart" emails.

    ⭐️⭐️⭐️⭐️✨
    4.5 stars average rating

    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

    Want to brush up on modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

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

    Created by Swizec with ❤️