Guest User

Untitled

a guest
Jan 16th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class Products {
  2. constructor(User) {
  3. if (typeof User !== "object") {
  4. throw new Error("User object is required to initialize products class");
  5. return false;
  6. }
  7. this.currentUser = User;
  8. this.data = [];
  9. }
  10.  
  11. checkPrivilege(permision) {
  12. const userHasThisPermission = this.currentUser.permissions.some(
  13. currentPermission => permision === currentPermission,
  14. );
  15.  
  16. return userHasThisPermission;
  17. }
  18.  
  19. add(product) {
  20. if (this.checkPrivilege("product_add")) {
  21. this.data.push(product);
  22. return true;
  23. }
  24.  
  25. return false;
  26. }
  27.  
  28. remove(product) {
  29. if (this.checkPrivilege("product_remove")) {
  30. this.data = this.data.filter(
  31. currentProduct => product !== currentProduct,
  32. );
  33.  
  34. return true;
  35. }
  36.  
  37. return false;
  38. }
  39.  
  40. reports() {
  41. if (this.checkPrivilege("product_reports")) {
  42. return `Products reports`;
  43. }
  44.  
  45. return false;
  46. }
  47. }
  48.  
  49. class User {
  50. constructor(name, permissions) {
  51. this.name = name;
  52. this.permissions = permissions;
  53. }
  54. }
  55.  
  56. const run = () => {
  57. const productInstanceWithUser1 = new Products(
  58. new User("Ricardo", ["product_reports"]),
  59. );
  60.  
  61. console.log(
  62. `User without access to add method tries add new product `,
  63. productInstanceWithUser1.add("New product"),
  64. );
  65.  
  66. console.log(
  67. `User without access to add method tries remove product `,
  68. productInstanceWithUser1.remove("New product"),
  69. );
  70.  
  71. console.log(
  72. `User with access to report method tries generates a report `,
  73. productInstanceWithUser1.reports(),
  74. );
  75. };
  76.  
  77. run();
Add Comment
Please, Sign In to add comment