Lesson 8 of 10
Arrays and tuples
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
A fixed length, and the original array stays put
Explanation
The type number[] is an array of numbers of any length. A tuple like [string, number] has a fixed length and a type for each position: the first element is a string and the second is a number.
The compiler doesn't infer tuples on its own. [["Layan", 82]] is inferred as (string | number)[][], and the difference between the name and the score is lost.
The type readonly Entry[] is a read-only array: it has no push, no sort, and no other method that changes the array itself. Use it for function parameters that have no business changing what they receive.
This catches a common mistake: sort sorts the original array in place and returns that same array, so the caller's data gets reordered without anyone asking for it. The fix is to copy it first: [...entries].sort(...).
Your task
Define type Entry = [string, number] and make it the element type of board. Make the parameter of ranked a readonly Entry[], and have the function return a copy sorted by score from highest to lowest, leaving the original array unchanged.
Checks
6 checks- No type errors
- Entry is a tuple of a string followed by a number
- Entry rejects the reverse order
- The compiler knows the element types of board
- ranked accepts a read-only array
- ranked sorts a copy and leaves the original alone