More array extensions

by yong

JavaScript

Array.prototype.skip = function(count) {
    var val,
        length = this.length;
    
    if(length > count) {
        val = this.slice(count);
    } else {
        val = [];            
    }
    
    return val;
};

Array.prototype.take = function(count) {
    var val,
        length = this.length;
    
    if(count > length) {
        count = length;
    }
        
    return this.slice(0, count);
};

Array.prototype.first = function() {
    var val;
    
    return this.length ? this[0] : this;
};

Array.prototype.last = function(count) {
    var val,
        length = this.length;
        
    return length ? this[length - 1] : this;
};

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(arr.first());

console.log(arr.last());

console.log(arr.take(3));

console.log(arr.skip(3));