Skip to content

Instantly share code, notes, and snippets.

Created January 1, 2013 14:20
Show Gist options
  • Save anonymous/4427822 to your computer and use it in GitHub Desktop.
Save anonymous/4427822 to your computer and use it in GitHub Desktop.
Array#slice returns an array with the seleted range of items. Because a new array is created every time you use this method, however, all these arrays are in memory, which means the JavaScript GC (Garbage Collection) has to collect up all of these unused arrays and throw them away. In performance-critical situations, such as in a game-loop that …
Array.prototype.slice_mutate = (function () {
var i;
return function slice_mutate(from, to) {
// first we set the array's length to the item at the "to" position
this.length = to;
// any items that were after the "to" position will be discarded
// from the first item...
i = 0;
// ...loop through all items before the "from" position...
while (i < from) {
// ...removing each item as we go
this.shift();
i++;
}
// we have now removed all items before the "from" position
// and after the "to" position
// and so the array now contains a slice of items between positions
// "from" and "to".
return this;
};
})();
// console shim
(function () {
if (!window.console) { window.console = {}; }
var c = window.console;
if (!c.log) { c.log = function () { }; }
if (!c.group) { c.group = function (label) { c.log("__" + label + "__"); }; }
if (!c.groupEnd) { c.groupEnd = function () { }; }
})();
// tests
var a = ["a", "b", "c", "d"];
console.group("a.slice(1,3)");
console.log("a: ", a);
console.log("returns: ", a.slice(1, 3));
console.log("after: ", a);
console.groupEnd();
var b = ["a", "b", "c", "d"];
console.group("b.slice_mutate(1,3)");
console.log("returns: ", b.slice_mutate(1, 3));
console.log("after: ", b);
console.groupEnd();
@christiaanwesterbeek
Copy link

Out of curiosity. Why is the prototype function slice_mutate written as a disclosure? Why not like this:

Array.prototype.slice_mutate = function (from, to) {
    var i;

    // first we set the array's length to the item at the "to" position
    this.length = to;
    // any items that were after the "to" position will be discarded

    // from the first item...
    i = 0;
    // ...loop through all items before the "from" position...
    while (i < from) {
        // ...removing each item as we go
        this.shift();

        i++;
    }

    // we have now removed all items before the "from" position
    //    and after the "to" position
    // and so the array now contains a slice of items between positions
    //    "from" and "to".
    return this;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment