Skip to content

Instantly share code, notes, and snippets.

@atimca
Created June 19, 2020 09:19
Show Gist options
  • Select an option

  • Save atimca/b14d8c8fb31c5c9079ebe63bac03cdc2 to your computer and use it in GitHub Desktop.

Select an option

Save atimca/b14d8c8fb31c5c9079ebe63bac03cdc2 to your computer and use it in GitHub Desktop.
func combine<State, Event>(_ reducers: (State, Event) -> State...) -> (State, Event) -> State {
return { state, event in
reducers.reduce(state) { state, reducer in
reducer(state, event)
}
}
}
func transform<GlobalState, GlobalEvent, LocalState, LocalEvent>(
localReducer: @escaping (LocalState, LocalEvent) -> LocalState,
stateKeyPath: WritableKeyPath<GlobalState, LocalState?>,
toLocalEvent: @escaping (GlobalEvent) -> LocalEvent?
) -> (GlobalState, GlobalEvent) -> GlobalState {
return { globalState, globalEvent in
guard
let localEvent = toLocalEvent(globalEvent),
let localState = globalState[keyPath: stateKeyPath]
else { return globalState }
var globalState = globalState
globalState[keyPath: stateKeyPath] = localReducer(localState, localEvent)
return globalState
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment