Codegen Helper

2025-01-12 19:40:59

Codegen Helper

CodegenContext.ts
test.ts
          class CodegenContext {
  code = ''
  private level = 0

  push(code: string) {
    this.code += code
  }

  newline(indent?: number) {
    this.push(`\n${'  '.repeat(indent ?? this.level)}`)
  }

  indent() {
    this.newline(++this.level)
  }

  deindent(noNewline = false) {
    if (noNewline) {
      --this.level
    } else {
      this.newline(--this.level)
    }
  }
}

        
          const ctx = new CodegenContext()

ctx.push('function sum(a, b){')
ctx.indent()
ctx.push('return a + b')
ctx.deindent()
ctx.push('}')


console.log(ctx.code)

// "function sum(a, b){
//   return a + b
// }"

        
© 2021-2025 sunshj's Blog