Factory Design Pattern

A factory function is a function which returns a new object. In JavaScript, any function can return an object. When it does so without the new keyword, it's a factory function.

Example

The following form passes the entered employee data to a factory function which creates a new Employee object, including derived properties like full name and email address.

Homethe GitHub logo: OctoCatView full factory.ts on GitHub
interface EmployeeData {
  firstName: string;
  lastName: string;
  jobTitle: string;
}

function createEmployee(
  emp: EmployeeData,
  domain: string,
): Employee {
  const id = generateEmployeeId();
  const fullName = generateFullName(emp);
  const email = generateEmail(emp, domain);

  return {
    id,
    ...emp,
    fullName,
    email,
  };
}

const employee = createEmployee(emp, "example.com");