Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert function for arrays #199

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions test/array.builders.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
9 changes: 9 additions & 0 deletions underscore.array.builders.js
Original file line number Diff line number Diff line change
Expand Up @@ -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; };

Expand Down Expand Up @@ -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');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this check is too restrictive, because splice also works with arguments and similar array-like objects. I think you can just remove this line.

splice.call(array, index, 0, item);
return array;
}

});
Expand Down