import { State } from '../types' ; import * as dot from '../utils/dot-prop' ; type Subscribe < TValues > = ( e : State < TValues > ) => void ; type Subscribers < TValues = { } > = Array < Subscribe < TValues > > ; export function createState < T extends State < T > > ( initialState = Object . assign ( { } ) ) { let state = initialState ; let subscribers = [ ] ; function get ( ) { return state ; } function subscribe ( fn ) { subscribers = [ ... subscribers , fn ] ; return ( ) => { subscribers = subscribers . filter ( l => l !== fn ) ; } ; } function set ( nextState ) { state = nextState ; notify ( ) ; } function patch ( path , next ) { const nextState = dot . set ( state , path , next ) ; state = nextState ; notify ( ) ; } function getPropertyValue ( path ) { return dot . get ( state , path ) ; } function getInitialPropertyValue ( path ) { return dot . get ( initialState , path ) ; } function getInitialState ( ) { return initialState ; } function notify ( ) { subscribers . forEach ( fn => { fn ( get ( ) ) ; } ) ; } return { get , set , patch , subscribe , getPropertyValue , getInitialState , getInitialPropertyValue } ; }