Skip to content

StringBuffer

reference
1 min readUpdated

Kind: Type

Source: src/utils/html.ts

Part of: Utils

StringBuffer contains string and Promise alternately The length of the array will be odd, the odd numbered element will be a string, and the even numbered element will be a Promise. When concatenating into a single string, it must be processed from the tail.

StringBuffer stores alternating string and Promise<string> values for HTML assembly. Its array length is odd: odd-numbered elements are strings, even-numbered elements are Promise<string>, and consumers must concatenate entries from the tail to preserve output order.

Definition

ts
(string | Promise<string>)[]

Diagram

mermaid
graph LR
  Start["String segment"] --> Async["Promise&lt;string&gt;"]
  Async --> End["String segment"]
  End --> Tail["Process from tail"]
  Tail --> HTML["Combined HTML string"]

Usage

ts
import type { StringBuffer } from './utils/html';

const buffer: StringBuffer = [
  '<article>',
  Promise.resolve('<p>Loaded content</p>'),
  '</article>',
];

async function joinBuffer(buffer: StringBuffer): Promise<string> {
  let html = '';

  for (const entry of [...buffer].reverse()) {
    html = `${await entry}${html}`;
  }

  return html;
}

const html = await joinBuffer(buffer);
// <article><p>Loaded content</p></article>

AI Coding Instructions

  • Keep entries alternating between string and Promise<string>, with strings at the beginning and end.
  • Preserve the odd-length array shape when creating or transforming a StringBuffer.
  • Concatenate entries from the tail; processing from the head can produce incorrect ordering around async content.
  • Await promise entries before prepending their resolved HTML to the accumulated output.

Was this page helpful?

Download as PDF
StringBuffer — Hono (narrator proof)