-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript_example.js
More file actions
121 lines (106 loc) · 3.06 KB
/
Copy pathjavascript_example.js
File metadata and controls
121 lines (106 loc) · 3.06 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* JavaScript Example for Code Translator
* Demonstrates translation to Python
*
* Expected Python output:
* ----------------------
* import asyncio
* from dataclasses import dataclass
* from typing import Optional
*
* @dataclass
* class User:
* id: int
* name: str
* email: str
* created_at: str
*
* class UserService:
* def __init__(self, api_url: str):
* self.api_url = api_url
* self._cache = {}
*
* async def fetch_user(self, user_id: int) -> Optional[User]:
* if user_id in self._cache:
* return self._cache[user_id]
*
* async with aiohttp.ClientSession() as session:
* async with session.get(f"{self.api_url}/users/{user_id}") as response:
* if response.status != 200:
* return None
* data = await response.json()
* user = User(**data)
* self._cache[user_id] = user
* return user
*/
// User data class
class User {
constructor(id, name, email, createdAt) {
this.id = id;
this.name = name;
this.email = email;
this.createdAt = createdAt;
}
toJSON() {
return {
id: this.id,
name: this.name,
email: this.email,
created_at: this.createdAt
};
}
}
// Service class for user operations
class UserService {
constructor(apiUrl) {
this.apiUrl = apiUrl;
this._cache = new Map();
}
async fetchUser(userId) {
// Check cache first
if (this._cache.has(userId)) {
return this._cache.get(userId);
}
try {
const response = await fetch(`${this.apiUrl}/users/${userId}`);
if (!response.ok) {
return null;
}
const data = await response.json();
const user = new User(
data.id,
data.name,
data.email,
data.created_at
);
// Cache the result
this._cache.set(userId, user);
return user;
} catch (error) {
console.error(`Failed to fetch user ${userId}:`, error);
return null;
}
}
async fetchMultipleUsers(userIds) {
// Fetch multiple users in parallel
const promises = userIds.map(id => this.fetchUser(id));
const users = await Promise.all(promises);
return users.filter(user => user !== null);
}
clearCache() {
this._cache.clear();
}
}
// Arrow function examples
const formatUserName = (user) => `${user.name} <${user.email}>`;
const filterActiveUsers = (users) =>
users.filter(u => u.createdAt > '2024-01-01');
// Async IIFE example
(async () => {
const service = new UserService('https://api.example.com');
const user = await service.fetchUser(123);
if (user) {
console.log('Found user:', formatUserName(user));
}
})();
module.exports = { User, UserService, formatUserName, filterActiveUsers };