Commit 39a42e51 authored by Jakob Moser's avatar Jakob Moser
Browse files

Make State a class

parent ad05af4e
Loading
Loading
Loading
Loading
+10 −9
Original line number Diff line number Diff line
/** Read and modify the current state of the application. Allows saving to local storage. */

export const currentState = {

export class State {
    /**
     * Return if this is the first time the application was started
     */
@@ -10,7 +9,7 @@ export const currentState = {
        // firstStart === null: If the key firstStart doesn't even exist, we certainly started for the first time
        // firstStart === "true": Local storage can only store strings, so this is our way of casting to boolean
        return firstStart === null || firstStart === "true"
    },
    }

    /**
     * Set if this is the first time the application was started
@@ -21,7 +20,7 @@ export const currentState = {
        }

        localStorage.setItem("firstStart", value)
    },
    }

    /**
     * Get the index of the exercise the user is currently working on
@@ -33,7 +32,7 @@ export const currentState = {
        } else {
            return parseInt(exerciseIndex, 10)
        }
    },
    }

    /**
     * Set the index of the exercise the user is currently working on.
@@ -48,14 +47,14 @@ export const currentState = {
        // throw new Error(`Exercise index must be >= 0 and < exercises.length (${pooltest.exercises.length})`)

        localStorage.setItem("exerciseIndex", index)
    },
    }

    /**
     * Get a list of indices of all solved exercises
     */
    get solvedExercises() {
        return JSON.parse(localStorage.getItem("solvedExercises")) || []
    },
    }

    /**
     * Private setter for the list of all solved exercises
@@ -63,7 +62,7 @@ export const currentState = {
     */
    _setSolvedExercises(indices) {
        localStorage.setItem("solvedExercises", JSON.stringify(indices))
    },
    }

    /**
     * Mark the given exercise as solved
@@ -80,7 +79,7 @@ export const currentState = {
        const newIndices = this.solvedExercises
        newIndices.push(exerciseIndex)
        this._setSolvedExercises(newIndices)
    },
    }

    /**
     * Return a string representation of the current state
@@ -89,3 +88,5 @@ export const currentState = {
        return JSON.stringify(this)
    }
}

export const currentState = new State()