MediumPro challengePythonJavaScriptTypeScript
Dependency Inversion Principle
Clean CodeSOLIDDIP
High-level modules should not depend on low-level modules — both should depend on abstractions.
// dirty — UserService is hardcoded to MySQLUserRepo
class MySQLUserRepo {
constructor(db) { this.db = db; }
findById(id) { return this.db[id]; }
}
class UserService {
constructor() { this.repo = new MySQLUserRepo({}); } // hardcoded!
getUser(id) { return this.repo.findById(id); }
}Refactor solve(db, id): instead of hardcoding the repo, create a simple in-memory repo from db (a plain object) and return db[id]. The point: solve receives its data source — it doesn't instantiate one.
solve({ u1: { id: 'u1', name: 'Alice' } }, 'u1') → { id: 'u1', name: 'Alice' }
Sample tests
Test #1Finds existing user
Input: [{"u1":{"id":"u1","name":"Alice"}},"u1"]
Output: {"id":"u1","name":"Alice"}
Test #2Multi-entry db, correct lookup
Input: [{"u2":{"id":"u2","name":"Bob"},"u3":{"id":"u3","name":"Carol"}},"u3"]
Output: {"id":"u3","name":"Carol"}
Test #3Missing id returns undefined/null
Input: [{"u1":{"id":"u1","name":"Alice"}},"u99"]
Output: null