function createConnection(url) {
const parsed = new URL(url);
return { host: parsed.hostname, port: parsed.port };
}
const conn = createConnection('http://localhost:3000');Use a factory to hide constructor complexity like parsing or validation.
The factory can hide complex initialization logic from the caller.
Challenge: Implement a createConnection(host, port) factory that returns a connection object with:
host and port propertiesisConnected property (initially false)connect() method that sets isConnected to truedisconnect() method that sets isConnected to falseExample:
const conn = createConnection('localhost', 5432)
conn.isConnected // false
conn.connect()
conn.isConnected // true