All files StateHandler.js

100% Statements 20/20
100% Branches 12/12
100% Functions 1/1
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92                        40x               17x                     22x 11x 11x 11x 11x               6x 6x 4x   6x               3x 3x 2x   3x                 6x 4x   6x               10x               4x        
/**
 * @author Michael Duve <mduve@designmail.net>
 * @file State pattern
 * @copyright Michael Duve 2016
 */
export class StateHandler {
 
    /**
     * get current state
     * @return {Object} current state from STATES-array
     */
    get current() {
        return this.states[this.i];
    }
 
    /**
     * get number of states
     * @return {Number} number of states
     */
    get length() {
        return this.states.length;
    }
 
    /**
     * @constructor
     * @param  {Array} states_array = [{value: 0, description: 'Default'}] - [description]
     * @return {StateHandler} instance of StateHandler for chaining
     */
    constructor(states_array = [{
        value: 0,
        description: 'Default'
    }]) {
        this.states = states_array;
        this.i = 0;
        this.lastState = this.current;
        return this;
    }
 
    /**
     * get the next element
     * @return {StateHandler} instance of StateHandler for chaining
     */
    next() {
        this.lastState = this.current;
        if (this.hasNext()) {
            this.i++;
        }
        return this;
    }
 
    /**
     * get the previous element
     * @return {StateHandler} instance of StateHandler for chaining
     */
    previous() {
        this.lastState = this.current;
        if (this.hasPrevious()) {
            this.i--;
        }
        return this;
    }
 
    /**
     * change the state to specified state
     * @param {Number} state - index of state in array
     * @return {StateHandler} instance of StateHandler for chaining
     */
    changeTo(state) {
        if (state >= 0 && state < this.length) {
            this.i = state;
        }
        return this;
    }
 
    /**
     * checks if there is a next element
     * @return {Boolean} wheter there is a next state or not
     */
    hasNext() {
        return this.i < this.length - 1;
    }
 
    /**
     * checks if there is a previous element
     * @return {Boolean} wheter there is a previous state or not
     */
    hasPrevious() {
        return this.i > 0;
    }
 
}