-
-
Save marksteve/79f3cc24119187e75c5ed5c1c5a5f678 to your computer and use it in GitHub Desktop.
Redux.ex (elixir)
This file contains hidden or 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 hidden or 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
| store = Redux.create_store fn state, action -> | |
| case action.type do | |
| :set -> | |
| action.value | |
| :add -> | |
| state + action.value | |
| _ -> | |
| state | |
| end | |
| end | |
| store = store |> Redux.dispatch(%{ type: :set, value: 2 }) | |
| IO.puts(store |> Redux.get_state()) #=> 2 | |
| store = Redux.dispatch(store, %{ type: :add, value: 10 }) | |
| IO.puts(store |> Redux.get_state()) #=> 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment