Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support repeatedly inserting at the same position. #5

Merged
merged 2 commits into from Jan 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/MagicString/index.js
Expand Up @@ -164,7 +164,14 @@ MagicString.prototype = {
} else if ( index === this.original.length ) {
this.append( content );
} else {
this.replace( index, index, content );
var mapped = this.locate(index);

if ( mapped === null ) {
throw new Error( 'Cannot insert at replaced character index: ' + index );
}

this.str = this.str.substr( 0, mapped ) + content + this.str.substr( mapped );
adjust( this.mappings, index, this.mappings.length, content.length );
}

return this;
Expand Down Expand Up @@ -220,6 +227,13 @@ MagicString.prototype = {
throw new Error( 'Cannot replace the same content twice' );
}

if ( firstChar > lastChar + 1 ) {
throw new Error(
'BUG! First character mapped to a position after the last character: ' +
'[' + start + ', ' + end + '] -> [' + firstChar + ', ' + ( lastChar + 1 ) + ']'
);
}

this.str = this.str.substr( 0, firstChar ) + content + this.str.substring( lastChar + 1 );

d = content.length - ( lastChar + 1 - firstChar );
Expand Down
6 changes: 6 additions & 0 deletions test/index.js
Expand Up @@ -203,6 +203,12 @@ describe( 'MagicString', function () {
var s = new MagicString( 'abcdefghijkl' );
assert.strictEqual( s.insert( 0, 'a' ), s );
});

it( 'should insert repeatedly at the same position correctly', function () {
var s = new MagicString( 'ab' );
assert.equal( s.insert(1, '1').toString(), 'a1b' );
assert.equal( s.insert(1, '2').toString(), 'a12b' );
});
});

describe( 'locate', function () {
Expand Down