What advantage does this factory function provide?
function createUser(name, email) {
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
if (!name) throw new Error('Name is required');
if (!email || !validateEmail(email)) throw new Error('Valid email is required');
return {
name,
email,
createdAt: new Date()
};
}
This factory function provides input validation before object creation: 1) It ensures all required data is present and valid before creating the object, 2) It throws helpful error messages when validation fails, 3) It prevents creation of invalid objects, 4) The validation logic is encapsulated within the factory, 5) Private helper functions (validateEmail) keep the validation logic organized, 6) This ensures that all created objects are in a valid state from the beginning.