Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Created September 9, 2025 14:03
Show Gist options
  • Save honzabrecka/bd1dd74b17926984f5cfd9add868c4ab to your computer and use it in GitHub Desktop.
Save honzabrecka/bd1dd74b17926984f5cfd9add868c4ab to your computer and use it in GitHub Desktop.
type Trace = string | { open: true } | { open: false };
type TraceTree = Array<string | TraceTree>;
const toTree = (trace: Array<Trace>): TraceTree => {
let currentBranch: TraceTree = [];
const path: TraceTree[] = [currentBranch];
const closeBranch = () => {
const closedBranch = path.pop()!;
currentBranch = path[path.length - 1];
currentBranch.push(closedBranch);
};
trace.forEach((item, i, all) => {
if (typeof item === 'string') {
currentBranch.push(item);
} else if (item.open === true) {
currentBranch = [];
path.push(currentBranch);
} else if (item.open === false) {
closeBranch();
}
// close all remaining open branches
if (i === all.length - 1) {
while (path.length > 1) {
closeBranch();
}
}
});
return currentBranch;
};
test('toTree', () => {
expect(toTree([])).toEqual([]);
expect(toTree(['foo'])).toEqual(['foo']);
expect(
toTree(['foo', { open: true }, 'bar', { open: false }, 'baz'])
).toEqual(['foo', ['bar'], 'baz']);
expect(
toTree([
'1',
{ open: true },
'2',
{ open: true },
'3',
'4',
{ open: false },
'5',
{ open: false },
'6',
{ open: true },
'7',
{ open: false }
])
).toEqual(['1', ['2', ['3', '4'], '5'], '6', ['7']]);
});
test('toTree unclosed', () => {
expect(toTree(['1', { open: true }, '2', { open: true }, '3', '4'])).toEqual([
'1',
['2', ['3', '4']]
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment