Passing Functions to map()

The finisher list in your port now excludes Lars Berg. Next on the timing desk’s report is the average finish time, and an average needs numbers. Every finish in the export is a string like "1:42:37", so the Python script turns each one into seconds first.

The helper hands int to map() by name, a Python habit you probably don’t think twice about. In this lesson, you’ll port the helper, see why the natural port gets Ana Ruiz’s finish wrong, and learn when to pass a function by name in JavaScript and when to write an arrow.

Pass a Converter by Name

In the Python script, to_seconds() splits the time on its colons and converts all three parts with map(int, ...), passing int itself rather than calling it:

Language: Python
def to_seconds(time):
    h, m, s = map(int, time.split(":"))
    return h * 3600 + m * 60 + s

print(to_seconds("1:42:37"))

Ana’s finish comes out as 6157 seconds. Python’s map() calls int once per piece, with that piece as its only argument.

Functions are values in JavaScript too, so you can pass one by name. The converter that reads digits from a string is parseInt(), so the line-by-line port passes it to .map() and unpacks the result with array destructuring, JavaScript’s h, m, s = .... Predict the result:

Language: JavaScript
const toSeconds = (time) => {
  const [h, m, s] = time.split(":").map(parseInt);
  return h * 3600 + m * 60 + s;
};

console.log(toSeconds("1:42:37"));
console.log("1:42:37".split(":").map(parseInt));

There’s no error, but the finish isn’t a number, and the second line shows where it went wrong:

Language: Program Output
NaN
[ 1, NaN, NaN ]

Only the hours survive, whereas Python’s map(int, ...) gives 1, 42, and 37.

See What map() Really Passes

JavaScript’s .map() doesn’t adapt to the function you give it. It always calls the callback, the function you pass to it, with three arguments: the item, its index, and the whole array. You can watch this happen with .forEach(), which calls its callback the same way:

Language: JavaScript
const parts = "1:42:37".split(":");
parts.forEach((item, index, array) => {
  console.log(item, index, array);
});

Each call gets the piece, its position, and the array it came from:

Language: Program Output
1 0 [ '1', '42', '37' ]
42 1 [ '1', '42', '37' ]
37 2 [ '1', '42', '37' ]

In Python, calling a one-parameter function with three arguments raises a TypeError. JavaScript lets you call a function with more arguments than it declares, and a function that has no parameter for the extras doesn’t use them, so nothing complains when .map() sends three. That’s where the Python habit stops carrying over, because a function with a second parameter gets the index in it.

The second parameter of parseInt() is the radix, the base it reads the digits in. It’s the same idea as the base parameter of Python’s int(), where int("37", 2) fails too. Python’s map() never passes it, but .map(parseInt) calls parseInt("1", 0), parseInt("42", 1), and parseInt("37", 2). A radix of 0 counts as no radix at all, so the hours come through in base 10. There’s no base 1, and 3 isn’t a binary digit, so the other two calls give NaN.

Pass Only What You Mean

The fix is a function that uses only the item. Number() takes one argument and ignores the rest, so .map(Number) is safe. For parseInt(), write an arrow to pass the item and the radix explicitly:

Language: JavaScript
console.log("1:42:37".split(":").map(Number));
console.log("1:42:37".split(":").map((s) => parseInt(s, 10)));

Both produce the three numbers Python’s map(int, ...) gives:

Language: Program Output
[ 1, 42, 37 ]
[ 1, 42, 37 ]

That’s the habit JavaScript developers keep. Pass a function by name only when you know it does nothing with an index and an array, and when in doubt, write the arrow and pass exactly what you mean.

.trim() needs the arrow for a different reason. The export’s cells carry stray spaces, like Mei’s " Mei Chen", and Python’s map(str.strip, cells) works because str.strip takes the string as its first argument. JavaScript’s .trim() takes no argument and works on the string it’s called on, which .map() never supplies, so the cell cleaner is cells.map((c) => c.trim()). Methods and their strings come back later, so that’s all you need for now.

Choose Between map() and forEach()

With toSeconds() fixed, the desk wants an array of seconds for the average and a printout to check against the timing company’s sheet, both from the six finishers’ times in finisher order. JavaScript gives each job its own method:

Language: JavaScript
const toSeconds = (time) => {
  const [h, m, s] = time.split(":").map(Number);
  return h * 3600 + m * 60 + s;
};

const finishTimes = [
  "1:42:37", "1:30:48", "1:36:20",
  "1:27:44", "1:35:03", "1:41:15",
];
const seconds = finishTimes.map(toSeconds);
console.log(seconds);

const logged = finishTimes.forEach((t) => {
  console.log(`${t} is ${toSeconds(t)} s`);
});
console.log(logged);

The first console.log() shows the new array. You normally don’t keep what .forEach() returns, but logged stores it here. .forEach() prints one line per finisher, and logged is undefined:

Language: Program Output
[ 6157, 5448, 5780, 5264, 5703, 6075 ]
1:42:37 is 6157 s
1:30:48 is 5448 s
1:36:20 is 5780 s
1:27:44 is 5264 s
1:35:03 is 5703 s
1:41:15 is 6075 s
undefined

Passing toSeconds by name is safe here because your helper uses only its first argument. Its body has braces, so it needs its return, or .map(toSeconds) gives six undefineds.

Use .map() when you want the new array, which it builds straight away, unlike Python’s lazy map(). Use .forEach() for a side effect such as logging. It returns undefined, much like a Python for loop that only calls print().

The seconds are ready for the average. First, though, the Python script uses comprehensions to build a dict of finish times by bib, the set of age groups, and a list of dicts for the results page. In the next lesson, Building Objects and Sets From Arrays, you’ll port them the JavaScript way: build an array, then turn it into what you need.

Become a Member to join the conversation.