Course outline
Full-Stack course / JavaScript fundamentals

Form field to number

Lab

How to fetch and submit this exercise

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each exercise: download it, edit the file named in the instructions, then submit.

gonomicon fetch fs-week-2/01-03-form-field-to-number
cd 01-03-form-field-to-number
gonomicon submit

The runner depends on the exercise: JavaScript/TypeScript/React labs run with Vitest, Python labs with pytest, and config-file labs (Docker, CI, Terraform, Nginx) are checked by parsing your file. gonomicon test runs the visible checks on your computer first; submitting also runs the hidden checks on our server.

Form field to number

Goal: take the text from a form field, turn it into a number, and say whether it was a usable number at all.

Worked example

Text typed into a form always arrives as a string. The file starts with a box called raw holding that text. The tests swap in other text, run your code, and read two boxes you create: usable and amount.

rawusableamount
"42"true42
"3.5"true3.5
"0"true0
"abc"falsenull
"12px"falsenull
""falsenull

Rules

  • Keep the line let raw = "..."; at the top of the file. The tests replace the text on it.
  • usable must be exactly true or false.
  • When usable is true, amount is the converted number (the number type, not text). When usable is false, amount is null.
  • Use the built-in Number(...) converter to decide what counts as a number. One exception: an empty field is never usable.
  • Compare with === and !==, never ==. Don't use var.
  • usable can be a const. amount may need to be a let if you fill it in later.
  • Text with spaces in it is not part of the tests.
  • To look at your boxes while you work, add console.log(usable, amount); at the bottom and run node form_field_to_number.js.

What you'll practice

  • Converting text to a number on purpose
  • Spotting a value that converts "successfully" but still isn't an answer
  • Making a choice with if

Run it

gonomicon fetch fs-week-2/01-03-form-field-to-number
cd 01-03-form-field-to-number
gonomicon test
gonomicon submit

Hints

  1. Add console.log(Number(raw)); and try "42", "abc" and "". Which of those answers would a person filling in a form be happy with?
  2. The empty string turns into a perfectly normal-looking number, so the converted value alone can't tell you the field was empty. Look at raw as well as the converted value.
  3. usable is true when raw is not the empty string and the converted number is not NaN. Then keep amount as null unless usable is true.