Skip to content

Commit

Permalink
Merge pull request #5 from eventualbuddha/insert-at-same-position-fails
Browse files Browse the repository at this point in the history
Support repeatedly inserting at the same position.
  • Loading branch information
Rich-Harris committed Jan 15, 2015
2 parents 0099dba + e200bbe commit f8f7e5b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
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

0 comments on commit f8f7e5b

Please sign in to comment.