Skip to content

Commit

Permalink
support getting magic string length
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford committed May 30, 2018
1 parent b32e32f commit bae0a4a
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.d.ts
Expand Up @@ -49,6 +49,7 @@ export class Bundle {
trimStart(charType?: string): Bundle;
trimEnd(charType?: string): Bundle;
isEmpty(): boolean;
length(): number;
}

export type ExclusionRange = [ number, number ];
Expand Down Expand Up @@ -96,6 +97,7 @@ export default class MagicString {
lastChar(): string;
lastLine(): string;
isEmpty(): boolean;
length(): number;

original: string;
}
4 changes: 4 additions & 0 deletions src/Bundle.js
Expand Up @@ -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]');
}
Expand Down
9 changes: 9 additions & 0 deletions src/MagicString.js
Expand Up @@ -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]');
}
Expand Down
19 changes: 19 additions & 0 deletions test/MagicString.js
Expand Up @@ -1192,6 +1192,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 ' );
Expand Down

0 comments on commit bae0a4a

Please sign in to comment.