loading...
Cover image for Elm Calculator Part 7 - Add Dirty State

Elm Calculator Part 7 - Add Dirty State

pianomanfrazier profile image Ryan Frazier Originally published at pianomanfrazier.com on ・2 min read

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
    }

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.

Posted on by:

pianomanfrazier profile

Ryan Frazier

@pianomanfrazier

I love static site generators, Elm, JavaScript and building things for the web. In my previous life I was a working classical pianist. I try to combine music and programming when I can.

Discussion

pic
Editor guide