UNPKG

reedx

Version:

Like redux but with less code

38 lines (25 loc) 1.06 kB
import isFunc from './isFunc' import reduce from './reduce' const { assign, keys } = Object const isObject = (obj) => obj === Object(obj) const isNull = (obj) => !obj && !isObject(obj) const isPrimitive = (state) => isNull(state) || (!isObject(state) && !isFunc(state)) const hasGetter = (prop) => prop && prop.get && isFunc(prop.get) export const getInState = (state, key) => hasGetter(state) ? state.get(key) : isObject(state) ? state[key] : state const stateAsProp = (name) => ({ [name]: (state) => getInState(state, name) }) const createSelector = (name, key) => (state) => getInState(getInState(state, name), key) const reduceState = (keys) => (name) => reduce(keys, (obj, key) => assign(obj, { [key]: createSelector(name, key) }), {}) const getMapKeys = (state) => hasGetter(state) ? [...state.keys()] : keys(state) const createSelectors = (name, { state, computed }) => { if (isPrimitive(state)) return stateAsProp(name) return assign(reduceState(getMapKeys(state))(name), computed || null) } export default createSelectors