all files / src/helpers/ create-local-state.js

100% Statements 23/23
100% Branches 6/6
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         11×                        
import templateText from './templated-text.js'
import {
    KEY_NOT_REGISTERED_ERROR
} from '../constants/language/helpers/create-local-state.js'
 
const createLocalState = (initialState) => {
    const state = Object.assign({}, initialState)
    return {
        set: (key, value) => setValue(key, value, state),
        get: function (key) {
            if (arguments.length === 0) return Object.assign({}, state)
            return getValue(key, state)
        }
    }
}
 
const setValue = (key, value, state) => {
    if (!(key in state)) throw makeUnregisteredKeyError(key)
    const oldValue = state[key]
    state[key] = value
    return oldValue
}
 
const getValue = (key, state) => {
    if (!(key in state)) throw makeUnregisteredKeyError(key)
    return state[key]
}
 
const makeUnregisteredKeyError = (key) => {
    const template = {'KEY': key}
    const errorMessage = templateText(KEY_NOT_REGISTERED_ERROR, template)
    return new Error(errorMessage)
}
 
export default createLocalState