javascript_sample.js•2.86 kB
/**
* Sample JavaScript file for testing parser feature parity
* @module UserService
*/
import { EventEmitter } from 'events';
import * as fs from 'fs';
import axios from 'axios';
// TODO: Add caching layer
// FIXME: Handle network errors properly
/**
* Represents a user in the system
* @class
*/
class User {
constructor(name, email, age = null) {
this.name = name;
this.email = email;
this.age = age;
}
toString() {
return `User(${this.name})`;
}
toJSON() {
return {
name: this.name,
email: this.email,
age: this.age
};
}
}
/**
* Service for managing users
* @extends EventEmitter
*/
export class UserService extends EventEmitter {
constructor(databaseUrl) {
super();
this.databaseUrl = databaseUrl;
this.users = new Map();
}
/**
* Add a new user to the service
* @param {User} user - The user to add
* @returns {boolean} True if user was added
* @throws {Error} If user data is invalid
*/
addUser(user) {
if (this.users.has(user.email)) {
return false;
}
if (!this._validateEmail(user.email)) {
throw new Error(`Invalid email: ${user.email}`);
}
this.users.set(user.email, user);
this.emit('userAdded', user);
return true;
}
/**
* Fetch all users asynchronously
* @async
* @returns {Promise<User[]>} Array of users
*/
async fetchUsers() {
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 100));
return Array.from(this.users.values());
}
/**
* Internal method to validate email format
* @private
*/
_validateEmail(email) {
return email.includes('@') && email.includes('.');
}
}
/**
* Process raw user data into User object
* @param {Object} data - Raw user data
* @returns {User|null} Processed user or null
*/
export const processUserData = (data) => {
try {
return new User(
data.name,
data.email,
data.age || null
);
} catch (error) {
// NOTE: Consider logging this error
console.error('Error processing user data:', error);
return null;
}
};
// Arrow function example
export const createUserService = (url) => new UserService(url);
// Async arrow function
export const loadUsersFromFile = async (filePath) => {
const data = await fs.promises.readFile(filePath, 'utf8');
return JSON.parse(data).map(processUserData);
};
// IIFE pattern
(function initializeService() {
const service = new UserService('postgresql://localhost/users');
global.userService = service;
})();
// Default export
export default UserService;