Skip to content

Commit a36c4d4

Browse files
committed
Mutate original array passed to insert function and return it
1 parent a14fbff commit a36c4d4

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

test/array.builders.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,9 @@ $(document).ready(function() {
209209
});
210210

211211
test('insert', function(){
212-
deepEqual(_.insert([], 0, 1), [1],'empty array will will insert item');
213-
deepEqual(_.insert([1,3], 1, 2), [1,2,3],'array will insert item');
214-
deepEqual(_.insert([1,3], 2, 2), [1,3,2],'exceeding index will insert item at the end');
212+
deepEqual(_.insert([], 0, 1), [1],'inserts item in empty array');
213+
deepEqual(_.insert([2], 0, 1), [1,2],'inserst item at the corret index');
214+
deepEqual(_.insert([1,2], 2, 3), [1,2,3],'inserts item at the end of array if exceeding index');
215+
deepEqual(_.insert([1,3], -1, 2), [1,2,3],'inserst item at the correct index if negative index');
215216
});
216217
});

underscore.array.builders.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
// Create quick reference variables for speed access to core prototypes.
1919
var slice = Array.prototype.slice;
20+
var splice = Array.prototype.splice;
2021

2122
var existy = function(x) { return x != null; };
2223

@@ -198,11 +199,11 @@
198199
},_.map(arguments[0],function(i){return [i];}));
199200
},
200201

201-
// Inserts an item in an array at the specific index
202+
// Inserts an item in an array at the specific index mutating the original
203+
// array and returning it.
202204
insert: function(array, index, item){
203-
var copy = array.slice(0);
204-
copy.splice(index, 0, item);
205-
return copy;
205+
splice.call(array, index, 0, item);
206+
return array;
206207
}
207208

208209
});

0 commit comments

Comments
 (0)