Skip to content

Instantly share code, notes, and snippets.

@ArnonEilat
Last active December 29, 2015 16:29

Revisions

  1. ArnonEilat revised this gist Nov 16, 2015. 1 changed file with 242 additions and 19 deletions.
    261 changes: 242 additions & 19 deletions Array.prototype.js
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,5 @@

    Array.prototype.insert = function(index, item) {
    this.splice(index, 0, item);
    this.splice(index, 0, item);
    };


    @@ -12,25 +11,249 @@ Array.prototype.insert = function(index, item) {
    * @returns {undefined}
    */
    Array.prototype.swap = function(first, second) {
    var firstIdx;
    var secondIdx;
    for (var i = 0; i < this.length; i++) {
    if (this[i] === first) {
    firstIdx = i;
    break;
    }
    var firstIdx;
    var secondIdx;
    for (var i = 0; i < this.length; i++) {
    if (this[i] === first) {
    firstIdx = i;
    break;
    }
    for (var i = 0; i < this.length; i++) {
    if (this[i] === second) {
    secondIdx = i;
    break;
    }
    }
    for (var i = 0; i < this.length; i++) {
    if (this[i] === second) {
    secondIdx = i;
    break;
    }
    }
    if (firstIdx === undefined || secondIdx === undefined)
    throw "Swap Exception";
    var tmp = this[firstIdx];
    this[firstIdx] = this[secondIdx];
    this[secondIdx] = tmp;
    };

    /**
    * Removes null and undefined elements from the array, turning it into a dense array.
    * Returns self for chaining purposes
    */
    Array.prototype.compact = function() {
    var changes = false;
    for (var i = 0; i < this.length; i++) {
    // If element is non-existent, undefined or null, remove it.
    if (!this[i]) {
    this.splice(i, 1);
    i = i - 1;
    changes = true;
    }
    if (firstIdx === undefined || secondIdx === undefined)
    throw "Swap Exception";
    var tmp = this[firstIdx];
    this[firstIdx] = this[secondIdx];
    this[secondIdx] = tmp;
    }
    if (!changes)
    return undefined;

    return this;
    };

    /**
    * Deletes the element at the specified index, returning that element, or undefined if the index is out of range.
    * A negative index is counted from the end of the array, where -1 corresponds to the last element. Returns self for chaining purposes.
    * Examples:
    * var a = ["ant", "bat", "cat", "dog"]
    * a.deleteAt(2) // => "cat"
    * a // => ["ant", "bat", "dog"]
    * a.deleteAt(99) // => undefined
    */
    Array.prototype.deleteAt = function(index) {
    if (index < 0)
    index = this.length + index;

    // If element is non-existent, return undefined:
    if (!this.hasOwnProperty(index))
    return undefined;

    var elem = this[index];
    this.splice(index, 1);
    return elem;
    };

    /**
    * Drops first n elements from array and returns the rest
    * of the elements in a new array.
    */
    Array.prototype.drop = function(n) {
    if (n < 0)
    throw new RangeError();

    return this.slice(n);
    };


    /**
    * Returns the first element, or the first n elements, of the array.
    * If the array is empty, requesting one element returns undefined ,
    * and requesting multiple elements returns an empty array.
    * Example:
    * var a = [ "q", "r", "s", "t" ]
    * a.first() // => "q"
    * a.first(2) // => ["q", "r"]
    */
    Array.prototype.first = function(n) {
    if (!n) {
    if (this.length === 0)
    return undefined;

    return this[0];
    } else {
    if (this.length === 0)
    return [];

    return this.slice(0, n);
    }
    };

    /**
    * Returns a new array that is a one-dimensional flattening of self (recursively).
    * That is, for every element that is an array, extract its elements into the new array.
    * The optional level argument determines the level of recursion to flatten.
    * Example:
    * var s = [ 1, 2, 3 ] // => [1, 2, 3]
    * var t = [ 4, 5, 6, [7, 8] ] // => [4, 5, 6, [7, 8]]
    * var a = [ s, t, 9, 10 ] // => [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
    * a.flatten() // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    * a = [ 1, 2, [3, [4, 5] ] ]
    * a.flatten(1) // => [1, 2, 3, [4, 5]]
    */
    Array.prototype.flatten = function(level) {
    if (!level)
    level = -1;

    function flatten_recursive(arr, level) {
    var result = [];
    arr.forEach(function(elem) {
    if (Array.isArray(elem)) {
    if (level !== 0)
    result = result.concat(flatten_recursive(elem, level - 1));
    else
    result.push(elem);
    } else {
    result.push(elem);
    }
    });
    return result;
    }
    return flatten_recursive(this, level);
    };


    /**
    * Inserts the given values before the element with the given index.
    * Negative indices count backwards from the end of the array, where -1 is the last element.
    * If a negative index is used, the given values will be inserted after that element,
    * so using an index of -1 will insert the values at the end of the array.
    * Example:
    * var a = ["a", "b", "c", "d"]
    * a.insert(2, 99) // => ["a", "b", 99, "c", "d"]
    * a.insert(-2, 1, 2, 3) // => ["a", "b", 99, "c", 1, 2, 3, "d"]
    */
    Array.prototype.insert = function(index) {
    if (index < 0)
    index = this.length + index + 1;

    if (index > this.length)
    index = this.length;

    for (var i = arguments.length - 1; i > 0; i--) {
    this.splice(index, 0, arguments[i]);
    }

    return this;
    };


    /**
    * Returns true if self contains no elements.
    */
    Array.prototype.isEmpty = function() {
    return this.length === 0;
    };


    /**
    * Returns the last element(s) of self.
    * If the array is empty, returns undefined if only one element requested.
    * Example:
    * var a = [ "w", "x", "y", "z" ]
    * a.last() // => "z"
    * a.last(2) // => ["y", "z"]
    */
    Array.prototype.last = function(n) {
    if (!n) {
    if (this.length === 0)
    return undefined;

    return this[this.length - 1];
    } else {
    var start = this.length - n;
    if (start < 0)
    start = 0;

    return this.slice(start, this.length);
    }
    };

    /**
    * Returns a new array with elements of self shuffled.
    */
    Array.prototype.shuffle = function() {
    var result = [];

    function get_random_int(max) {
    return Math.floor(Math.random() * max);
    }

    for (var i = 0; i < this.length; i++) {
    result.push(this[i]);
    }

    for (var i = 0; i < this.length; i++) {
    var to = Math.floor(Math.random() * (this.length - 1));
    var temp = result[i];
    result[i] = result[to];
    result[to] = temp;
    }

    return result;
    };


    /**
    * Returns a new array by removing duplicate values in self.
    * Comparison is done by default using the === operator.
    * If a function is given, it will use the return value of the function for comparison.
    * Example:
    * var a = [ "a", "a", "b", "b", "c" ]
    * a.uniq // => ["a", "b", "c"]
    * var b = [["student","sam"], ["student","george"], ["teacher","matz"]]
    * b.uniq (function(s) { return s[0]; }) // => [["student", "sam"], ["teacher", "matz"]]
    */
    Array.prototype.uniq = function(f) {
    var result = [];
    var found;
    for (var i = 0; i < this.length; i++) {
    found = false;
    for (var j = 0; j < result.length; j++) {
    if (!f) {
    if (result[j] === this[i]) {
    found = true;
    }
    } else {
    if (f(result[j]) === f(this[i])) {
    found = true;
    }
    }
    }
    if (!found) {
    result.push(this[i]);
    }
    }
    return result;
    };

  2. ArnonEilat revised this gist Apr 15, 2014. No changes.
  3. ArnonEilat created this gist Nov 28, 2013.
    36 changes: 36 additions & 0 deletions Array.prototype.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@

    Array.prototype.insert = function(index, item) {
    this.splice(index, 0, item);
    };


    /***
    * var swapTest=['a','b','c'];
    * swapTest.swap('a','c')
    * @param {type} first
    * @param {type} second
    * @returns {undefined}
    */
    Array.prototype.swap = function(first, second) {
    var firstIdx;
    var secondIdx;
    for (var i = 0; i < this.length; i++) {
    if (this[i] === first) {
    firstIdx = i;
    break;
    }
    }
    for (var i = 0; i < this.length; i++) {
    if (this[i] === second) {
    secondIdx = i;
    break;
    }
    }
    if (firstIdx === undefined || secondIdx === undefined)
    throw "Swap Exception";
    var tmp = this[firstIdx];
    this[firstIdx] = this[secondIdx];
    this[secondIdx] = tmp;
    };