JavaScript, lesson 3
Most programs need data from outside. In this course the data arrives on standard input (stdin): the tests type some text into your program, and your program reads it.
Node.js has a built-in module called fs (file system). Its readFileSync function reads a
whole file at once. Standard input is file descriptor 0, so passing 0 reads everything the
user typed until the input ends:
require("fs") loads the module. The "utf8" argument asks for a string; without it you would
get raw bytes (a Buffer). This reads lines in one go, which is perfect for programs
whose input is fully known when they start. Many people shorten it to one line:
2 exercises to try what you just read.
The input is one long string, for example "12\n30\n". Two string methods break it apart:
trim() removes spaces and line breaks from both ends.split(separator) cuts a string into an array of parts.When numbers are on one line separated by spaces, split on any run of whitespace with the
regular expression /\s+/:
"12" is a string, not a number. Adding two strings joins them: "12" + "30" is "1230".
Convert first with Number():
Number() insists the whole string is a number. parseInt("12kg", 10) and
parseFloat("3.5kg") are more forgiving and read the leading number, stopping at the first
character that does not fit. Always pass 10 to parseInt so it reads decimal digits.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Division always produces a decimal when needed. For whole-number division use
Math.floor(7 / 2) (which gives 3) or Math.trunc, which rounds toward zero and so differs
for negative numbers. The remainder operator keeps the sign of the left side: -7 % 3 is -1.
Shortcut operators update a variable in place: total += 5, count -= 1, price *= 2, and
i++ adds one.
toFixed(digits) formats a number with a fixed number of decimals and returns a string:
Math.round, Math.floor and Math.ceil round to whole numbers and return numbers.
The input has two integers, one per line. Print their sum.
Sample input:
Sample output:
You plan a movie marathon and know the total running time in minutes. Print how long that is
in hours and minutes, in the form H h M min.
The input is one line with a whole number of minutes (0 or more).
Sample input:
Sample output:
const fs = require("fs");
const input = fs.readFileSync(0, "utf8");const input = require("fs").readFileSync(0, "utf8");const lines = input.trim().split("\n"); // ["12", "30"]
const first = lines[0]; // "12" (arrays count from 0)const parts = "4 7 9".trim().split(/\s+/); // ["4", "7", "9"]const a = Number("12"); // 12
const b = Number(" 3.5 "); // 3.5 (surrounding spaces are fine)
const bad = Number("12kg"); // NaN, "not a number"const avg = 10 / 3;
console.log(avg.toFixed(2)); // 3.33
console.log((2.5).toFixed(0)); // 32
351352 h 15 min