diff --git a/src/MagicString.js b/src/MagicString.js index c9913b9..7bc5b7d 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -181,11 +181,11 @@ MagicString.prototype = { }, // get current location of character in original string - locate () { + locate ( character ) { throw new Error( 'magicString.locate is deprecated' ); }, - locateOrigin () { + locateOrigin ( character ) { throw new Error( 'magicString.locateOrigin is deprecated' ); }, @@ -290,6 +290,8 @@ MagicString.prototype = { let result = ''; + // TODO handle moves + for ( let i = 0; i < this.chunks.length; i += 1 ) { const chunk = this.chunks[i]; @@ -352,18 +354,36 @@ MagicString.prototype = { this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) return this; - do { - let lastChunk = this.chunks[ this.chunks.length - 1 ]; - if ( rx.test( lastChunk.content ) ) { - lastChunk.edit( lastChunk.content.replace( rx, '' ) ); - } + let charIndex = this.original.length; + let i = this.chunks.length; - if ( lastChunk.content.length || this.chunks.length === 1 ) { - break; - } else { - this.chunks.pop(); + while ( i-- ) { + const chunk = this.chunks[i]; + + if ( charIndex > chunk.end ) { + const slice = this.original.slice( chunk.end, charIndex ); + + const match = rx.exec( slice ); + if ( match ) { + this.chunk( charIndex - match[0].length, charIndex, '' ); + } + + if ( !match || match[0].length < slice.length ) { + // there is non-whitespace after the chunk + return this; + } } - } while ( true ); + + chunk.content = chunk.content.replace( rx, '' ); + if ( chunk.content ) return this; + + charIndex = chunk.start; + } + + const slice = this.original.slice( 0, charIndex ); + + const match = rx.exec( slice ); + if ( match ) this.chunk( charIndex - match[0].length, charIndex, '' ); return this; }, @@ -374,19 +394,34 @@ MagicString.prototype = { this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) return this; - do { - let firstChunk = this.chunks[0]; - if ( rx.test( firstChunk.content ) ) { - firstChunk.edit( firstChunk.content.replace( rx, '' ) ); - } + let charIndex = 0; - if ( firstChunk.content.length || this.chunks.length === 1 ) { - break; - } else { - this.chunks.shift(); + for ( let i = 0; i < this.chunks.length; i += 1 ) { + const chunk = this.chunks[i]; + + if ( charIndex < chunk.start ) { + const slice = this.original.slice( charIndex, chunk.start ); + + const match = rx.exec( slice ); + if ( match ) this.chunk( charIndex, charIndex + match[0].length, '' ); + + if ( !match || match[0].length < slice.length ) { + // there is non-whitespace before the chunk + return this; + } } - } while ( true ); + + chunk.content = chunk.content.replace( rx, '' ); + if ( chunk.content ) return this; + + charIndex = chunk.end; + } + + const slice = this.original.slice( charIndex, this.original.length ); + + const match = rx.exec( slice ); + if ( match ) this.chunk( charIndex, charIndex + match[0].length, '' ); return this; } -}; +}