4 ms·
The sample code is fine for JavaScript, but it begs to be written using pattern matching, like that in Elixir/Erlang. If you have the current state and an event
by brentjanderson 9y ago
The sample code is fine for JavaScript, but it begs to be written using pattern matching, like that in Elixir/Erlang. If you have the current state and an event to apply to that state (similar to Redux), you can pattern match on pieces of the current state and the event to apply to that state. Your event handler could look like:
```
def handle(%{state: "open", balance: balance},%Deposit{amount: amount}) do
{:ok, %{state: "open", balance: (balance + amount)}}
end
def handle(%{state: "closed"}, %Deposit{}) do
{:error, "invalid action: account closed"}
end
```
Every state/event pairing is explicitly defined as a variation of the `handle` method. There are countless ways to build a state machine like this, but the basic pattern matching primitive seems to simplify this a lot.
An extension to javascript to support this has been proposed, I'm hopeful that it gets considered seriously: https://github.com/tc39/proposal-pattern-matching https://github.com/tc39/proposal-pattern-matching