liveBook · Manning

Nested string

As explained in Building User-Friendly DSLs

A code-generation composition technique in which generated strings are embedded within other template strings.

A nested string is a string or arbitrarily deep array of strings, including multiline strings. Template functions return this flexible structure instead of manually concatenating fragments or joining lines. section 8.4.2

Array construction replaces both string concatenation and newline joining. The generator can compose template results declaratively, then convert the outermost structure into a writable string. section 8.4.2 section 8.5

Generating a React rental form

The indexJsx template returns imports, a mapped array of attribute initializers, and trailing code as one nested structure. asString flattens arrays, ensures newline endings, and joins the fragments before writing the generated file. section 8.4.2

Listing 8.14 The asString function in src/generator/template-utils.js
const withNewlineEnsured = (str) => str     #1
     + (str.endsWith("\n") ? "" : "\n")
const asString = (nestedString) =>
     Array.isArray(nestedString)       #2
    ? nestedString.flat(Infinity)      #3
        .map(withNewlineEnsured)      #4
        .join("")                            #5
    : withNewlineEnsured(nestedString)    #6

module.exports.asString = asString    #7

Inspect the asString implementation that recursively flattens nested arrays, normalizes newline endings, and joins the resulting strings. section 8.4.2

How Building User-Friendly DSLs covers it

How deep it goes
Defines the recursive structure and demonstrates flattening, newline normalization, and final joining; defers indentation details.
Examples
Uses a React rental-form generator, mapped attribute initializers, nested arrays, multiline literals, and the asString utility.
What it assumes
Assumes JavaScript functions and arrays while defining the nested composition mechanism directly through code-generation examples.
What you can do after
Build template functions that compose readable fragments and serialize them into properly formatted generated code.
How it connects
Connects template functions, ASTs, code generators, indentation, and code formatters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.