Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 18, 2019 02:34
Show Gist options
  • Save rxluz/776a3e152725f4524db374e2e669e11d to your computer and use it in GitHub Desktop.
Save rxluz/776a3e152725f4524db374e2e669e11d to your computer and use it in GitHub Desktop.
S.O.L.I.D Principles for JS with examples, see more at https://medium.com/p/db95b44e82e
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
setName(name) {
this.name = name;
}
setAge(age) {
this.age = age;
}
}
class UserLogProxy {
constructor() {
this.logs = [];
}
get(target, propKey, receiver) {
const UserLogScope = this;
if (propKey === "logs") {
return {
get: () => this.getLogs(),
};
}
const targetValue = Reflect.get(target, propKey, receiver);
if (typeof targetValue === "function") {
return function(...args) {
UserLogScope.add(`Edited user ${propKey.replace("set", "")}`);
return targetValue.bind(this, args);
};
} else {
return targetValue;
}
}
getLogs() {
return this.logs;
}
add(message) {
this.logs.push(message);
}
}
const run = () => {
const UserInstanceWithLogs = new Proxy(
new User("Ricardo", 32),
new UserLogProxy(),
);
UserInstanceWithLogs.setAge(33);
UserInstanceWithLogs.setName("Ricardo Luz");
console.log(UserInstanceWithLogs.logs.get());
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment