DEV Community

Cover image for Elm Calculator Part 7 - Add Dirty State
Ryan Frazier
Ryan Frazier

Posted on • Originally published at pianomanfrazier.com on

Elm Calculator Part 7 - Add Dirty State

This post is part of a series. To see all published posts in the series see the tag "elm calculator book".If you wish to support my work you can purchase the 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.

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.

Dirty State

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
    }
Enter fullscreen mode Exit fullscreen mode

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
        }
Enter fullscreen mode Exit fullscreen mode

The next chapter is going to add support for users to enter numbers into the calculator using their number pad on their keyboard.

Discussion (0)