Skip to content

Instantly share code, notes, and snippets.

@Robbert
Created March 15, 2014 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Robbert/9573713 to your computer and use it in GitHub Desktop.
Save Robbert/9573713 to your computer and use it in GitHub Desktop.
/**
* @author Robbert Broersma <http://robbertbroersma.nl/>
* @license © 2013, The Knights Who Say NIH B.V. All rights reserved.
*/
var List = {};
/**
* Works like arr.splice(), but without constructing an array
* with the removed values to reduce garbage collection.
*
* Same combination as Node.removeChild() vs Node.remove().
*
* @param {Array} arr
* @param {number} start
* @param {number} howMany
*/
List.removeSlice = function (arr, start, howMany)
{
var before,
after,
newIndex,
newLength,
oldIndex,
end,
l = arr.length;
if (start < 0)
start += l;
end = start + howMany;
if (start < end)
{
if (start <= 0 && end >= l)
{
while (l--)
arr.pop();
}
else if (start === 0)
{
while (end--)
arr.shift();
}
else if (end === l)
{
end -= start;
while (end--)
arr.pop();
}
else
{
before = start;
after = l - start - howMany
if (after > before)
{
while (end --> start)
{
arr[start] = arr[0];
arr.shift();
}
}
else
{
oldIndex = start + howMany;
newIndex = start;
newLength = l - howMany;
while (newIndex < newLength)
{
arr[newIndex] = arr[oldIndex];
oldIndex++;
newIndex++;
}
while (howMany--)
arr.pop();
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment