Elm quick tip: restricting a number
08 Feb 2016
Here is a quick tip for restricting a number in Elm. I came across an interesting function in the standard library while building a form with some number inputs. I wanted to keep the numbers entered by the user restricted to a known range. Consider the following code:
In this example, whenever the user types a level into the character-level input, the program sends a message tagged with the ModifyLevel
action and the level to the update
function. The program restricts the level by calling restrictLevel
on the data passed to the update
function.
Here is my original, long-winded restrictLevel
function:
This effectively prevents the user from typing in a number outside of the range 1 to 20. It turns out the Elm standard library has a function for this exact situation which can save you quite a bit of typing. The function is called clamp
(read about it on the Elm docs)*. Here is my refactored restrictLevel
function:
*Note that at the time of this writing, I was using Elm core v3.0.0
If you want to follow along as I learn to build a business, you can follow me on Twitter or enter your email below.
Email subscribers will know first when I write new articles and release products. I value your trust and will repay it in kind.
Further Reading
- What is Functional Progamming? by Kris Jenkins