Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Products {
- constructor(User) {
- if (typeof User !== "object") {
- throw new Error("User object is required to initialize products class");
- return false;
- }
- this.currentUser = User;
- this.data = [];
- }
- checkPrivilege(permision) {
- const userHasThisPermission = this.currentUser.permissions.some(
- currentPermission => permision === currentPermission,
- );
- return userHasThisPermission;
- }
- add(product) {
- if (this.checkPrivilege("product_add")) {
- this.data.push(product);
- return true;
- }
- return false;
- }
- remove(product) {
- if (this.checkPrivilege("product_remove")) {
- this.data = this.data.filter(
- currentProduct => product !== currentProduct,
- );
- return true;
- }
- return false;
- }
- reports() {
- if (this.checkPrivilege("product_reports")) {
- return `Products reports`;
- }
- return false;
- }
- }
- class User {
- constructor(name, permissions) {
- this.name = name;
- this.permissions = permissions;
- }
- }
- const run = () => {
- const productInstanceWithUser1 = new Products(
- new User("Ricardo", ["product_reports"]),
- );
- console.log(
- `User without access to add method tries add new product `,
- productInstanceWithUser1.add("New product"),
- );
- console.log(
- `User without access to add method tries remove product `,
- productInstanceWithUser1.remove("New product"),
- );
- console.log(
- `User with access to report method tries generates a report `,
- productInstanceWithUser1.reports(),
- );
- };
- run();
Add Comment
Please, Sign In to add comment