mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-09 18:37:50 +00:00
Don't mutate array during #remove. [closes #1079]
This commit is contained in:
committed by
jdalton
parent
b1a81a85b1
commit
d2b98323dd
@@ -5310,17 +5310,32 @@
|
|||||||
function remove(array, predicate, thisArg) {
|
function remove(array, predicate, thisArg) {
|
||||||
var index = -1,
|
var index = -1,
|
||||||
length = array ? array.length : 0,
|
length = array ? array.length : 0,
|
||||||
result = [];
|
result = [],
|
||||||
|
removes = 0,
|
||||||
|
indexes = [],
|
||||||
|
last;
|
||||||
|
|
||||||
predicate = getCallback(predicate, thisArg, 3);
|
predicate = getCallback(predicate, thisArg, 3);
|
||||||
while (++index < length) {
|
while (++index < length) {
|
||||||
var value = array[index];
|
var value = array[index];
|
||||||
if (predicate(value, index, array)) {
|
if (predicate(value, index, array)) {
|
||||||
|
if (last && last[0] + last[1] === index) {
|
||||||
|
++last[1];
|
||||||
|
} else {
|
||||||
|
last = [index - removes, 1];
|
||||||
|
indexes.push(last);
|
||||||
|
}
|
||||||
result.push(value);
|
result.push(value);
|
||||||
splice.call(array, index--, 1);
|
++removes;
|
||||||
length--;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
index = -1;
|
||||||
|
length = indexes.length;
|
||||||
|
while (++index < length) {
|
||||||
|
last = indexes[index];
|
||||||
|
splice.call(array, last[0], last[1]);
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12417,6 +12417,13 @@
|
|||||||
_.remove(array, function(num) { return num == null; });
|
_.remove(array, function(num) { return num == null; });
|
||||||
deepEqual(array, [1, 3]);
|
deepEqual(array, [1, 3]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should not mutate the array until all elements to remove are determined', 1, function() {
|
||||||
|
var array = [1, 2, 3];
|
||||||
|
|
||||||
|
_.remove(array, function(num, i) { return i % 2 == 0; });
|
||||||
|
deepEqual(array, [2]);
|
||||||
|
});
|
||||||
}());
|
}());
|
||||||
|
|
||||||
/*--------------------------------------------------------------------------*/
|
/*--------------------------------------------------------------------------*/
|
||||||
|
|||||||
Reference in New Issue
Block a user