diff --git a/index.d.ts b/index.d.ts index f725754..5fb722c 100644 --- a/index.d.ts +++ b/index.d.ts @@ -49,6 +49,7 @@ export class Bundle { trimStart(charType?: string): Bundle; trimEnd(charType?: string): Bundle; isEmpty(): boolean; + length(): number; } export type ExclusionRange = [ number, number ]; @@ -96,6 +97,7 @@ export default class MagicString { lastChar(): string; lastLine(): string; isEmpty(): boolean; + length(): number; original: string; } diff --git a/src/Bundle.js b/src/Bundle.js index 779676f..76fa317 100644 --- a/src/Bundle.js +++ b/src/Bundle.js @@ -235,6 +235,10 @@ export default class Bundle { return true; } + length() { + return this.sources.reduce((length, source) => length + source.content.length(), this.intro.length); + } + trimLines() { return this.trim('[\\r\\n]'); } diff --git a/src/MagicString.js b/src/MagicString.js index 47c1503..7c3890a 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -632,6 +632,15 @@ export default class MagicString { return true; } + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while (chunk = chunk.next); + return length; + } + trimLines() { return this.trim('[\\r\\n]'); } diff --git a/test/MagicString.js b/test/MagicString.js index 0880bf1..6e86c0d 100644 --- a/test/MagicString.js +++ b/test/MagicString.js @@ -1198,6 +1198,25 @@ describe( 'MagicString', () => { }); }); + describe( 'length', () => { + it( 'should support length', () => { + const s = new MagicString( ' abcde fghijkl ' ); + + assert.equal( s.length(), 17 ); + + s.prepend( ' ' ); + s.append( ' ' ); + s.remove( 1, 6 ); + s.remove( 9, 15 ); + + assert.equal( s.length(), 6 ); + + s.remove( 15, 16 ); + + assert.equal( s.length(), 5 ); + }); + }); + describe( 'lastLine', () => { it( 'should support lastLine', () => { const s = new MagicString( ' abcde\nfghijkl ' );