Skip to content

Commit f64fb1f

Browse files
authored
Update codereview.js
1 parent f1f52a0 commit f64fb1f

File tree

1 file changed

+55
-17
lines changed

1 file changed

+55
-17
lines changed

‎codereview.js‎

Lines changed: 55 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,66 @@
1-
// Function to calculate the sum of an array
1+
// Base API URL (parameterized for better maintainability)
2+
const API_BASE_URL = "https://jsonplaceholder.typicode.com";
3+
4+
// Function to calculate the sum of an array (using reduce for better readability)
25
function calculateSum(array) {
3-
let sum = 0;
4-
for (let i = 0; i < array.length; i++) {
5-
sum += array[i];
6+
if (!Array.isArray(array)) {
7+
throw new TypeError("Input must be an array of numbers.");
68
}
7-
return sum;
9+
return array.reduce((sum, num) => sum + num, 0);
810
}
911

10-
// Function to fetch user data from an API
12+
// Function to fetch user data from an API with error handling
1113
async function fetchUserData(userId) {
12-
const url = "https://jsonplaceholder.typicode.com/users/" + userId;
13-
let response = await fetch(url);
14-
let data = await response.json();
15-
console.log("User Data:", data);
16-
return data;
14+
try {
15+
const url = `${API_BASE_URL}/users/${userId}`;
16+
const response = await fetch(url);
17+
if (!response.ok) {
18+
throw new Error(`API call failed with status ${response.status}`);
19+
}
20+
const data = await response.json();
21+
console.log("User Data:", data);
22+
return data;
23+
} catch (error) {
24+
console.error("Error fetching user data:", error.message);
25+
return null;
26+
}
1727
}
1828

19-
// Function to format a user's full name
29+
// Function to format a user's full name safely
2030
function formatFullName(user) {
21-
return user.first_name + " " + user.last_name;
31+
if (
32+
!user ||
33+
typeof user.firstName !== "string" ||
34+
typeof user.lastName !== "string"
35+
) {
36+
console.warn("Invalid user object. Returning 'Unknown User'.");
37+
return "Unknown User";
38+
}
39+
return `${user.firstName} ${user.lastName}`;
40+
}
41+
42+
// Function to process multiple users and calculate their total ID sum
43+
async function processUsers(userIds) {
44+
const results = [];
45+
for (const userId of userIds) {
46+
const user = await fetchUserData(userId);
47+
if (user) {
48+
const fullName = formatFullName(user);
49+
console.log("Processed User:", fullName);
50+
results.push({ id: user.id, fullName });
51+
}
52+
}
53+
const totalIdSum = calculateSum(results.map((user) => user.id));
54+
console.log("Total User ID Sum:", totalIdSum);
55+
return results;
2256
}
2357

2458
// Test the functions
25-
console.log("Sum:", calculateSum([1, 2, 3, 4]));
26-
fetchUserData(1).then((user) => {
27-
console.log("Formatted Name:", formatFullName(user));
28-
});
59+
(async () => {
60+
try {
61+
const users = await processUsers([1, 2, 3]);
62+
console.log("Processed Users:", users);
63+
} catch (error) {
64+
console.error("Unexpected error during processing:", error.message);
65+
}
66+
})();

0 commit comments

Comments
 (0)