Created
          September 9, 2025 14:03 
        
      - 
      
- 
        Save honzabrecka/bd1dd74b17926984f5cfd9add868c4ab to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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