Reading a Spec
Reading a spec
Up to now you have read code and predicted what it does. From here you write it.Every task in this set is a spec: a short description of a function somebody needs. A spec always tells you three things, and it is worth naming them before you type anything.
• The name of the function, and the parameters it takes. These have to be spelled exactly as written, because the tests call your function by that name.
• What has to come back out of it, and what kind of value that is: a number, a true or false, or a string.
• The rule connecting them.
Hand the value back
A function that prints a value and a function that gives one back are not the same function, and only one of them is any use to the code that called it.return ends the function and sends a value out to the call. console.log puts characters on the screen and sends nothing anywhere. A function with no return hands back undefined, and undefined is what the caller then has to work with.
One test you can see, several you cannot
Each problem shows you one test case. Its job is to show you the shape of the answer, so you can see whether a number, a true or false, or a string is expected.The rest of the tests are hidden. If one fails you are told which one, and nothing else. That is on purpose: the hidden cases sit at exactly the places where a nearly-right answer goes wrong, and a hidden case that showed you its input could be answered rather than solved.
| What the spec contains | The case worth checking yourself |
|---|---|
| A rule written as 'or less', 'or more', 'at least' | The number named in the rule, exactly |
| A rule written as 'more than', 'under', 'after' | The number named in the rule, exactly |
| A division by some count | A count of zero |
| A subtraction | The case where the result drops below zero |
| Money, or a measurement | A value that does not come out whole |
| A formula with two inputs | Two inputs that are not equal to each other |
The function below was written from the spec in its comment, and it has one mistake at an edge. The main program checks it on three moisture levels. Run it, then change it and run it again:
• Repair the comparison, so that the result for 35 percent agrees with the spec.
• Add a check of your own for 36 percent, below the others.
• Press Reset, then change
return moisture < 35; to console.log(moisture < 35);.// Spec: needsWater(moisture) gives back true when a plant
// needs water. It needs water at 35 percent moisture or less.
function needsWater(moisture) {
return moisture < 35;
}
// Main program
console.log("29 percent:", needsWater(29));
console.log("58 percent:", needsWater(58));
console.log("35 percent:", needsWater(35));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.