From a9c4b92493146deab38570e503172095ade3bb73 Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Sun, 11 Dec 2016 09:43:54 -0500 Subject: [PATCH] fix prepending code to builders --- src/utils/CodeBuilder.js | 24 +++++++++++++++---- src/utils/__test__.js | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/utils/CodeBuilder.js b/src/utils/CodeBuilder.js index e40acd5b8e..1caaf9ff84 100644 --- a/src/utils/CodeBuilder.js +++ b/src/utils/CodeBuilder.js @@ -12,33 +12,49 @@ export default class CodeBuilder { addLine ( line ) { if ( this.last === BLOCK ) { this.result += `\n\n${line}`; - } else { + } else if ( this.last === LINE ) { this.result += `\n${line}`; + } else { + this.result += line; } this.last = LINE; + if ( !this.first ) this.first = LINE; } addLineAtStart ( line ) { if ( this.first === BLOCK ) { this.result = `${line}\n\n${this.result}`; - } else { + } else if ( this.first === LINE ) { this.result = `${line}\n${this.result}`; + } else { + this.result += line; } this.first = LINE; + if ( !this.last ) this.last = LINE; } addBlock ( block ) { - this.result += `\n\n${block}`; + if ( this.result ) { + this.result += `\n\n${block}`; + } else { + this.result += block; + } this.last = BLOCK; + if ( !this.first ) this.first = BLOCK; } addBlockAtStart ( block ) { - this.result = `${block}\n\n${this.result}`; + if ( this.result ) { + this.result = `${block}\n\n${this.result}`; + } else { + this.result += block; + } this.first = BLOCK; + if ( !this.last ) this.last = BLOCK; } isEmpty () { diff --git a/src/utils/__test__.js b/src/utils/__test__.js index 7768021a1d..54e173d5f9 100644 --- a/src/utils/__test__.js +++ b/src/utils/__test__.js @@ -118,4 +118,55 @@ describe( 'CodeBuilder', () => { // line 4 ` ); }); + + it( 'adds a line at start', () => { + const builder = new CodeBuilder(); + + builder.addLine( '// second' ); + builder.addLineAtStart( '// first' ); + + assert.equal( builder.toString(), deindent` + // first + // second + ` ); + }); + + it( 'adds a line at start before a block', () => { + const builder = new CodeBuilder(); + + builder.addBlock( '// second' ); + builder.addLineAtStart( '// first' ); + + assert.equal( builder.toString(), deindent` + // first + + // second + ` ); + }); + + it( 'adds a block at start', () => { + const builder = new CodeBuilder(); + + builder.addLine( '// second' ); + builder.addBlockAtStart( '// first' ); + + assert.equal( builder.toString(), deindent` + // first + + // second + ` ); + }); + + it( 'adds a block at start before a block', () => { + const builder = new CodeBuilder(); + + builder.addBlock( '// second' ); + builder.addBlockAtStart( '// first' ); + + assert.equal( builder.toString(), deindent` + // first + + // second + ` ); + }); });