-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.html
More file actions
91 lines (77 loc) · 2.7 KB
/
content.html
File metadata and controls
91 lines (77 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Groups music track titles by release year and sorts them alphabetically.
*
* @param {Object[]} tracks - An array of music track objects.
* @returns {Object} - An object where the keys are years and values are sorted arrays of track titles.
* @throws {Error} - If the input is not an array or contains invalid track objects.
*/
function getMusicTitlesByYear(tracks) {
if (!Array.isArray(tracks)) {
throw new Error("Invalid input: Expected an array of music track objects.");
}
// Check if there is no data (empty array)
if (tracks.length === 0) {
throw new Error("No data: The tracks array is empty.");
}
const result = {};
for (const track of tracks) {
if (
typeof track !== "object" ||
!track.title ||
typeof track.title !== "string" ||
!track.artist ||
typeof track.artist !== "string" ||
!track.year ||
typeof track.year !== "number" ||
isNaN(track.year)
) {
throw new Error("Invalid track data: Each track must have a string title, string artist ,a numeric year and must not be empty."); }
if (!result[track.year]) {
result[track.year] = [];
}
result[track.year].push(track.title);
}
// Sort titles alphabetically for each year
for (const year in result) {
result[year].sort();
}
return result;
}
// Predefined input
const tracks = [
{ title: 'Blinding Lights', artist: 'The Weeknd', year: 2020 },
{ title: 'Levitating', artist: 'Dua Lipa', year: 2021 },
{ title: 'Save Your Tears', artist: 'The Weeknd', year: 2020 },
];
try {
console.log(getMusicTitlesByYear(tracks));
} catch (error) {
console.error(error.message);
}
/* Expected Output:
{
2020: ['Blinding Lights', 'Save Your Tears'],
2021: ['Levitating']
}
*/
// Error Handling Test Cases
try {
console.log(getMusicTitlesByYear("invalid input"));
} catch (error) {
// console.error(error.message); // Expected: "Invalid input: Expected an array of music track objects."
}
try {
console.log(getMusicTitlesByYear([{ title: "Song X", artist: "Artist X" }]));
} catch (error) {
// console.error(error.message); // Expected: "Invalid track data: Each track must have a string title and a numeric year."
}
try {
console.log(getMusicTitlesByYear([{artist: "Artist X" }]));
} catch (error) {
// console.error(error.message); // Expected: "Invalid track data: Each track must have a string title and a numeric year."
}
try {
console.log(getMusicTitlesByYear([])); // No data case
} catch (error) {
// console.error(error.message); // Expected: "No data: The tracks array is empty."
}