First, last and the middle

Report the first word, the last word and how many are between them.

What to build

A program that uses destructuring and a default rather than indexes.

Requirements

  • Read a line of words.
  • Print first: W.
  • Print last: W. With only one word, it is both first and last.
  • Print middle: N, the number of words between the first and the last.

Input

One line of words separated by single spaces.

Output

Three lines.

Constraints

There are from 1 to 100 words.

Example

Input:

a b c d

Output:

first: a
last: d
middle: 2

Why it works

Rest puts everything after the first word in its own list, so the first word needs no special handling. ?? covers the single case where that list is empty.

Examples

Example 1 · Input
a b c d
Expected output
first: a
last: d
middle: 2
Example 2 · Input
x y
Expected output
first: x
last: y
middle: 0

Hints

Hint 1

const [first, ...rest] = words puts the remaining words in rest.

Hint 2

rest.at(-1) is the last item, and it is undefined if rest is empty.

Hint 3

?? can fall back to first when there is only one word.

Solution

Show one correct solution (try it yourself first)
const [first, ...rest] = prompt().split(" ");
const last = rest.at(-1) ?? first;
console.log(`first: ${first}`);
console.log(`last: ${last}`);
console.log(`middle: ${Math.max(rest.length - 1, 0)}`);

Lesson: Destructuring, spread and safe access →