Skip to content

Commit

Permalink
Ensure inserting at position 0 is consistent with non-zero positions.
Browse files Browse the repository at this point in the history
When inserting at non-zero positions the string is placed after any
previous strings that would have been placed at that position. Before
this commit, inserting at position 0 was treated specially, deferring
to the `prepend` operation. This commit changes the behavior of inserts
at 0 to match inserts at any other position. If the old behavior is
desired, `prepend` should be called directly.
  • Loading branch information
eventualbuddha committed Apr 2, 2015
1 parent 2271c63 commit dcb7945
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
4 changes: 1 addition & 3 deletions src/MagicString/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,7 @@ MagicString.prototype = {
throw new TypeError( 'inserted content must be a string' );
}

if ( index === 0 ) {
this.prepend( content );
} else if ( index === this.original.length ) {
if ( index === this.original.length ) {
this.append( content );
} else {
var mapped = this.locate(index);
Expand Down
10 changes: 8 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,12 @@ describe( 'MagicString', function () {
assert.equal( s.insert(1, '2').toString(), 'a12b' );
});

it( 'should insert repeatedly at the beginning correctly', function () {
var s = new MagicString( 'ab' );
assert.equal( s.insert(0, '1').toString(), '1ab' );
assert.equal( s.insert(0, '2').toString(), '12ab' );
});

it( 'should throw when given non-string content', function () {
var s = new MagicString( '' );
assert.throws(
Expand Down Expand Up @@ -423,8 +429,8 @@ describe( 'MagicString', function () {
s.prepend( 'xyz' );
assert.equal( s.toString(), 'xyzabcdefghijkl' );

s.prepend( 'xyz' );
assert.equal( s.toString(), 'xyzxyzabcdefghijkl' );
s.prepend( '123' );
assert.equal( s.toString(), '123xyzabcdefghijkl' );
});

it( 'should return this', function () {
Expand Down

0 comments on commit dcb7945

Please sign in to comment.