Skip to content

Commit

Permalink
Disallow non-string content.
Browse files Browse the repository at this point in the history
Without this it’s quite easy to accidentally pass an array, which may
seem to just work but will have the wrong length, causing further
operations at or after the affected location to be wrong.
  • Loading branch information
eventualbuddha committed Mar 23, 2015
1 parent a562439 commit 355dd79
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/MagicString/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ MagicString.prototype = {
},

append: function ( content ) {
if ( typeof content !== 'string' ) {
throw new TypeError( 'appended content must be a string' );
}

this.str += content;
return this;
},
Expand Down Expand Up @@ -165,6 +169,10 @@ MagicString.prototype = {
},

insert: function ( index, content ) {
if ( typeof content !== 'string' ) {
throw new TypeError( 'inserted content must be a string' );
}

if ( index === 0 ) {
this.prepend( content );
} else if ( index === this.original.length ) {
Expand Down Expand Up @@ -224,6 +232,10 @@ MagicString.prototype = {
},

replace: function ( start, end, content ) {
if ( typeof content !== 'string' ) {
throw new TypeError( 'replacement content must be a string' );
}

var firstChar, lastChar, d;

firstChar = this.locate( start );
Expand Down
24 changes: 24 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ describe( 'MagicString', function () {
var s = new MagicString( 'abcdefghijkl' );
assert.strictEqual( s.append( 'xyz' ), s );
});

it( 'should throw when given non-string content', function () {
var s = new MagicString( '' );
assert.throws(
function () { s.append( [] ); },
TypeError
);
});
});

describe( 'clone', function () {
Expand Down Expand Up @@ -263,6 +271,14 @@ describe( 'MagicString', function () {
assert.equal( s.insert(1, '1').toString(), 'a1b' );
assert.equal( s.insert(1, '2').toString(), 'a12b' );
});

it( 'should throw when given non-string content', function () {
var s = new MagicString( '' );
assert.throws(
function () { s.insert( 0, [] ); },
TypeError
);
});
});

describe( 'locate', function () {
Expand Down Expand Up @@ -466,6 +482,14 @@ describe( 'MagicString', function () {
var s = new MagicString( 'abcdefghijkl' );
assert.strictEqual( s.replace( 3, 4, 'D' ), s );
});

it( 'should throw when given non-string content', function () {
var s = new MagicString( '' );
assert.throws(
function () { s.replace( 0, 1, [] ); },
TypeError
);
});
});

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

0 comments on commit 355dd79

Please sign in to comment.