Build a Run-Once Typewriter Component for a Hidden Token
Data Structure DesignModel answerLast updated
Build a React and TypeScript component that finds a hidden token in the DOM or over HTTP, types it out every 50ms, never replays the animation, cleans up after itself, and has Mocha tests.
Task
You have a small React + TypeScript project that uses Mocha for tests. Build a component, plus any helpers it needs, that obtains a secret token (the "flag") and reveals it on screen one character at a time.
1. Obtaining the token
The component must support two sources.
DOM mode. Read the token from the current document. It can be in either of these places:
- an element with a
data-flag="..."attribute whose value is the whole token, or - an element with
id="flag"whose text content is the token.
The element may be concealed (display:none, the hidden attribute, and similar). It must still be found.
HTTP mode. Send GET <flagUrl>. The response is one of:
- JSON of the form
{ "flag": "FLAG{...}" }, or - plain text such as
FLAG{...}.
2. Typewriter display
After the token is known, show it progressively.
- Render into a container such as
<div data-testid="flag-output">...</div>. - Add one character every 50 ms. The delay may be a prop so tests can control it.
- When typing ends, the whole token stays on screen.
3. Run only once
If the component re-renders because of state or prop changes, the animation must not start over after it has finished.
4. Engineering constraints
- Nothing may leak. Timers and in-flight requests must be cancelled when the component unmounts.
- Code must tolerate both browser and Node test environments. For example,
documentmight be undefined.
5. Tests
Write Mocha tests (or structure the code so an automated grader can verify it) covering:
- DOM extraction for both the
data-flagcase and the#flagcase. - HTTP parsing for both JSON and plain-text bodies.
- The typewriter reveals characters over time and finishes.
- The animation does not restart after a re-render.
Deliverables
- A component (for example
FlagViewer) and its helper functions. - Mocha tests that confirm the behavior above.
Explain your design choices and the trade-offs you made.
Hints
Hint 1
Separate the work into three layers: pure retrieval helpers that accept the document or fetch function as a parameter, a typing hook, and a thin component that connects them. Each layer can then be tested alone.
Hint 2
Hidden elements are still in the DOM tree. Think about which text-reading property depends on rendered layout and which one does not.
Hint 3
State alone is a weak place to record that the animation has finished. Consider what survives a re-render, or a StrictMode mount/cleanup/mount cycle, without triggering extra renders, and how an effect should behave when it re-runs.
Hint 4
For cleanup, pair every interval with a clearInterval, give each request an AbortController, and ignore the abort error caused by unmounting.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into three parts that can be tested independently.
- Pure helpers for getting the token.
extractFlagFromDom(doc)receives the document as an argument. The browser/Node difference is handled at the edge: if no document exists, it returnsnull.parseFlagBody(text)andfetchFlag(url, signal, fetchImpl)deal with HTTP mode. The fetch function is injectable, so tests can pass a stub and never touch the network.
- A
useTypewriterhook that stores progress in refs. - A thin
FlagViewercomponent that wires the two together and is responsible for cleanup.
Key decisions
Hidden elements: use textContent, not innerText. innerText depends on layout and returns an empty string for display:none content. textContent and getAttribute read the raw DOM, so hidden nodes are no problem. querySelector('[data-flag]') and getElementById('flag') also ignore CSS visibility. Trim the result, and if data-flag is empty, fall back to #flag.
JSON vs plain text. Trim the body and try JSON.parse. Accept the parsed value only if it is an object with a string flag property. In every other case, including when parsing throws, return the trimmed body. A bare FLAG{...} is not valid JSON, so it correctly reaches the fallback. Check res.ok first and throw on non-2xx.
Run once. Keep the typing index in a useRef and a doneRef boolean latch. Refs persist across re-renders and across the React 18 StrictMode mount/cleanup/mount sequence, so the effect resumes from the stored index and returns immediately once the latch is set. Do not depend on state that resets. In addition, the component locks in the first token it receives and never refetches, so the hook's input does not change after loading.
No leaks. Every setInterval is cleared in the effect cleanup and also when typing completes. Each request gets an AbortController, aborted on unmount, plus a cancelled flag to prevent setState after unmount. An AbortError is swallowed because it is expected.
Code
// flag.ts
export function extractFlagFromDom(
doc: Document | null | undefined =
typeof document !== "undefined" ? document : undefined
): string | null {
if (!doc) return null;
const attr = doc.querySelector("[data-flag]")?.getAttribute("data-flag")?.trim();
if (attr) return attr;
const byId = doc.getElementById("flag")?.textContent?.trim();
return byId || null;
}
export function parseFlagBody(body: string): string {
const trimmed = body.trim();
try {
const parsed: unknown = JSON.parse(trimmed);
if (parsed && typeof parsed === "object" &&
typeof (parsed as any).flag === "string") {
return (parsed as { flag: string }).flag.trim();
}
} catch { /* plain text */ }
return trimmed;
}
export type FetchLike = (
url: string,
init?: { signal?: AbortSignal }
) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;
export async function fetchFlag(
url: string,
signal?: AbortSignal,
fetchImpl: FetchLike = (u, i) => fetch(u, i)
): Promise<string> {
const res = await fetchImpl(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return parseFlagBody(await res.text());
}
// useTypewriter.ts
import { useEffect, useRef, useState } from "react";
export function useTypewriter(text: string | null, speedMs = 50) {
const [count, setCount] = useState(0);
const countRef = useRef(0);
const doneRef = useRef(false);
useEffect(() => {
if (!text || doneRef.current) return;
const id = setInterval(() => {
countRef.current = Math.min(countRef.current + 1, text.length);
setCount(countRef.current);
if (countRef.current >= text.length) {
doneRef.current = true;
clearInterval(id);
}
}, speedMs);
return () => clearInterval(id);
}, [text, speedMs]);
return { displayed: text ? text.slice(0, count) : "", done: doneRef.current };
}
// FlagViewer.tsx
import React, { useEffect, useState } from "react";
import { extractFlagFromDom, fetchFlag, FetchLike } from "./flag";
import { useTypewriter } from "./useTypewriter";
type Props = {
mode: "dom" | "http";
flagUrl?: string;
speedMs?: number;
doc?: Document | null;
fetchImpl?: FetchLike;
};
export function FlagViewer({ mode, flagUrl, speedMs = 50, doc, fetchImpl }: Props) {
const [flag, setFlag] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (flag !== null) return; // lock in first token
if (mode === "dom") {
const f = extractFlagFromDom(doc);
f ? setFlag(f) : setError("Flag not found");
return;
}
if (!flagUrl) { setError("Missing flagUrl"); return; }
const controller = new AbortController();
let cancelled = false;
fetchFlag(flagUrl, controller.signal, fetchImpl)
.then(f => { if (!cancelled) setFlag(f); })
.catch(e => {
if (!cancelled && e?.name !== "AbortError") setError(String(e.message ?? e));
});
return () => { cancelled = true; controller.abort(); };
}, [mode, flagUrl, doc, fetchImpl, flag]);
const { displayed } = useTypewriter(flag, speedMs);
return (
<div>
{error && <p role="alert">{error}</p>}
<div data-testid="flag-output">{displayed}</div>
</div>
);
}
Testing strategy
Run Mocha with ts-node/register and jsdom-global/register, and use Sinon fake timers so tests are fast and deterministic.
- DOM: build a document with a hidden
data-flagelement, then one with a hidden#flagelement. Assert the extracted value. Also assert thatnullis returned whendocisundefined. - HTTP: pass a stub
fetchImplreturning a JSON body, then a plain-text body, then a non-2xx response (expect a rejection). - Typing: render, advance the clock by 50 ms several times, and assert the output grows by one character each tick. After
length * 50ms the full token is shown. - Once only: after completion, call
rerenderwith new props (for example a differentspeedMs) and advance time. The text must stay complete and never reset to empty. - Cleanup: unmount mid-animation, advance the clock, and assert no state-update warnings and no pending timers. For HTTP, assert the signal was aborted.
Complexity
- Time: O(n) timer ticks for an n-character token. Each render slices the string, so the copying totals O(n²), which is negligible for flag-sized strings.
- Space: O(n). There is one interval and at most one request at any moment.
Edge cases and trade-offs
- No
document(plain Node): returnnulland show an error rather than throw. - Empty
data-flagfalls through to#flag; surrounding whitespace is trimmed. - Network failure, non-2xx status, or a missing
flagUrldisplay an error message. - Empty token: nothing is animated.
- If
speedMschanges mid-animation, typing continues from the current index at the new speed. - If
flagUrlchanges after the token loaded, nothing happens. This deliberately favors the "never restart" rule; state it explicitly as a trade-off.
Common mistakes
- Using
innerText, which breaks for hidden elements. - Tracking the index only in state, or resetting it in the effect body, so the animation restarts.
- Forgetting
clearIntervalorabort()on unmount. - Touching
documentat module load, which crashes in Node. - Calling
fetchdirectly inside the component, which makes it hard to test.