пятница, 19 июля 2013 г.

Event List Functions

function EventList () {
    this.eventList = [];
    return this;
}

EventList.prototype.addEvent = function(event){
    this.eventList.push(event);
    return this;
};

EventList.prototype.removeEventByIndex = function(index){
    if (index > -1 && index < this.eventList.length) {
        Array.prototype.splice.call(this.eventList, index, 1);
    } else {
        return false;
    }
};

EventList.prototype.removeAllEvents = function(){
    this.eventList = [];
    return this;
};

EventList.prototype.countEvents = function(){
    return this.eventList.length;
};

EventList.prototype.getEventByIndex = function(index) {
    if (index > -1 && index < this.eventList.length) {
        return this.eventList[index];
    } else {
        return false;
    }
};

EventList.prototype.insertEventByIndex = function(event, index){
    if (index > -1 && index < this.eventList.length) {
        if (index === 0) {
            this.eventList.unshift(event);
        } else if (index > 0 && index <= this.eventList.length - 1) {
            var tempArray = Array.prototype.slice.call(this.eventList, 0, index);
            tempArray.push(event);
            this.eventList = tempArray.concat(Array.prototype.slice.call(this.eventList, index, this.eventList.length));
        } else if (index === eventList.length) {
            this.eventList.push(event);
        }
    } else {
        return false;
    }
};

EventList.prototype.indexOfEvent = function (event) {
    var eventListLength = this.eventList.length;
    while (eventListLength--) {
        if (this.eventList[eventListLength] === event) {
            return eventListLength;
        }
    }
    return false;
};

// TESTS

var events = new EventList();

events.addEvent('one');
events.addEvent('two');
console.log('1: ' + events.countEvents());
events.insertEventByIndex('three', 1);
console.log('2: ' + events.countEvents());
console.log('3: ' + events.getEventByIndex(0));
console.log('4: ' + events.getEventByIndex(1));
console.log('5: ' + events.indexOfEvent('three'));
events.removeEventByIndex(0);
console.log('6: ' + events.countEvents());
console.log('7: ' + events.indexOfEvent('three'));
events.removeAllEvents();
console.log('8: ' + events.countEvents());

Комментариев нет:

Отправить комментарий