diff --git a/test/array.builders.js b/test/array.builders.js index 892e6a9..02e8f41 100644 --- a/test/array.builders.js +++ b/test/array.builders.js @@ -208,4 +208,13 @@ $(document).ready(function() { deepEqual(_.combinations(["a",["b"]],[[1]]),[["a",[1]],[["b"],[1]]],'initial arrays can contain array elements which are then preserved'); }); + test('insert', function(){ + var throwingFn = function() { _.insert({}, 0, 1); }; + throws(throwingFn, TypeError, 'throws a TypeError when passing an object literal'); + + deepEqual(_.insert([], 0, 1), [1],'inserts item in empty array'); + deepEqual(_.insert([2], 0, 1), [1,2],'inserst item at the corret index'); + deepEqual(_.insert([1,2], 2, 3), [1,2,3],'inserts item at the end of array if exceeding index'); + deepEqual(_.insert([1,3], -1, 2), [1,2,3],'inserst item at the correct index if negative index'); + }); }); diff --git a/underscore.array.builders.js b/underscore.array.builders.js index 426657f..46aae9f 100644 --- a/underscore.array.builders.js +++ b/underscore.array.builders.js @@ -17,6 +17,7 @@ // Create quick reference variables for speed access to core prototypes. var slice = Array.prototype.slice; + var splice = Array.prototype.splice; var existy = function(x) { return x != null; }; @@ -196,6 +197,14 @@ })); },[]); },_.map(arguments[0],function(i){return [i];})); + }, + + // Inserts an item in an array at the specific index mutating the original + // array and returning it. + insert: function(array, index, item){ + if (!_.isArray(array)) throw new TypeError('Expected an array as the first argument'); + splice.call(array, index, 0, item); + return array; } });