This post is part of a series. If you wish to support my work you can purchase the PDF book on gumroad.
This project uses Elm version 0.19
- Part 1 - Introduction
- Part 2 - Project Setup
- Part 3 - Add CSS
- Part 4 - Basic Operations
- Part 5 - Adding Decimal Support
- Part 6 - Supporting Negative Numbers
- Part 7 - Add Dirty State (this post)
- Part 8 - Support Keypad Input
- Part 9 - Combination Key Input
- Part 10 - Testing
- Part 11 - Netlify Deployment
This allows users to overwrite the input area with a new number if the calculator is in a dirty state.
- browse: https://gitlab.com/pianomanfrazier/elm-calculator/-/tree/v0.7
- diff: https://gitlab.com/pianomanfrazier/elm-calculator/-/compare/v0.6...v0.7
- ellie: https://ellie-app.com/72p3SNcV8Fva1
The way it works is if a user has just entered a number in, the input area is now dirty. Users can press enter again to keep pushing that same number on the stack. Or they can start typing a new number and it will over-write the existing number.
We need to add another piece of state to our model.
type alias Model =
{ stack : List Float
, currentNum : String
, error : Maybe String
, dirty : Bool
}
initialModel : Model
initialModel =
{ stack = []
, currentNum = "0"
, error = Nothing
, dirty = False
}
In the model update we need to add some logic around when the input field is dirty.
We need to do this to the Clear
, Enter
, InputOperator
, SetDecimal
, SetSign
, and InputNumber
messages.
Note: When I initially wrote the code I forgot to flip the flag on SetDecimal
and SetSign
. The Master branch has this fix. v0.7 does not.
Clear ->
{ model | currentNum = "0", dirty = False }
Enter ->
...
{ model
| ...
, dirty = True
}
InputOperator operator ->
...
{ model
| ...
, dirty = True
}
InputNumber num ->
...
else if model.dirty then
{ model
| ...
, dirty = False
}
The next chapter is going to add support for users to enter numbers into the calculator using their number pad on their keyboard.