-
-
Save typesend/2f9068971261185d4206dcb48433ce65 to your computer and use it in GitHub Desktop.
Redux.ex (elixir)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Redux do | |
@moduledoc """ | |
Like redux.js, but more elixir-like | |
store = create_store fn state, action -> ... end | |
store |> get_state() | |
store |> dispatch(%{ type: "publish" }) | |
""" | |
defstruct reducer: nil, state: nil | |
@doc """ | |
Creates a store | |
""" | |
def create_store(reducer, initial_state \\ nil) do | |
%Redux{reducer: reducer, state: initial_state} | |
|> dispatch(%{ type: :"@@redux/INIT" }) | |
end | |
@doc """ | |
Returns the current state | |
""" | |
def get_state(store) do | |
store.state | |
end | |
@doc """ | |
Dispatches an action | |
""" | |
def dispatch(store, action) do | |
store | |
|> Map.put(:state, store.reducer.(get_state(store), action)) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Example do | |
import Redux | |
def reducer(state, action) do | |
case action.type do | |
:set -> | |
action.value | |
:add -> | |
state + action.value | |
_ -> | |
state | |
end | |
end | |
def run do | |
store = create_store(&reducer/2) | |
store = store |> dispatch(%{ type: :set, value: 2 }) | |
IO.puts(store |> get_state()) #=> 2 | |
store = dispatch(store, %{ type: :add, value: 10 }) | |
IO.puts(store |> get_state()) #=> 12 | |
end | |
end | |
Example.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment