From dcb79456bc291fe99fdff10e05d69c068f1e3ee0 Mon Sep 17 00:00:00 2001 From: Brian Donovan Date: Thu, 2 Apr 2015 08:40:17 -0700 Subject: [PATCH] Ensure inserting at position 0 is consistent with non-zero positions. 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. --- src/MagicString/index.js | 4 +--- test/index.js | 10 ++++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/MagicString/index.js b/src/MagicString/index.js index 5c03b77..571c5dd 100644 --- a/src/MagicString/index.js +++ b/src/MagicString/index.js @@ -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); diff --git a/test/index.js b/test/index.js index 639ba9c..e1e5086 100644 --- a/test/index.js +++ b/test/index.js @@ -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( @@ -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 () {