class User {
constructor(id, name, active = true) {
this.id = id;
this.name = name;
this.active = active;
}
toggleActiveStatus() {
this.active = !this.active;
console.log(`${this.name}'s status updated to: ${this.active ? 'Active' :
'Inactive'}`);
}
async updateUserDetails(newDetails) {
try {
const response = await fetch(`https://api.example.com/users/${this.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newDetails)
});
if (!response.ok) throw new Error('Failed to update user');
const data = await response.json();
console.log('User details updated:', data);
} catch (error) {
console.error(error.message);
}
}
}
const users = [
new User(1, 'John', true),
new User(2, 'Jane', false),
new User(3, 'Alice', true)
];
function getActiveUsers(users) {
return users.filter(user => user.active);
}
function handleUserInteraction(action, userId, details) {
const user = users.find(u => u.id === userId);
if (!user) {
console.log('User not found');
return;
}
switch (action) {
case 'toggle':
user.toggleActiveStatus();
break;
case 'update':
user.updateUserDetails(details);
break;
default:
console.log('Invalid action');
}
}
async function fetchUserData(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Unable to fetch user data');
const data = await response.json();
console.log('Fetched user data:', data);
} catch (error) {
console.error('Error:', error.message);
}
}
const activeUsers = getActiveUsers(users);
console.log('Active Users:', activeUsers);
// Simulate user interaction
handleUserInteraction('toggle', 1);
handleUserInteraction('update', 2, { name: 'Janet', active: true });
// Simulate an API call to fetch user data
fetchUserData('https://api.example.com/users');