Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class HandlerBase {
  2.     constructor(info) {
  3.         this.info = info;
  4.     }
  5.  
  6.     handler(action, value) {
  7.         switch (action) {
  8.             case 'changeName':
  9.                 this.info.name = value;
  10.                 break;
  11.             default:
  12.                 console.log('cannot match in default handler');
  13.         }
  14.     }
  15. }
  16.  
  17. class HobbiesHandler extends HandlerBase {
  18.     handler(action, value) {
  19.         super.handler(action, value);
  20.  
  21.         switch (action) {
  22.             case 'removeHobbies':
  23.                 this.info.hobbies = null;
  24.                 break
  25.             case 'addHobby':
  26.                 this.info.hobbies.push(value)
  27.                 break;
  28.             default:
  29.                 console.log('cannot match in any handlers');
  30.         }
  31.     }
  32. }
  33.  
  34. class AgeHandler extends HandlerBase {
  35.     handler(action, value) {
  36.         super.handler(action, action);
  37.  
  38.         switch (action) {
  39.             case 'changeAge':
  40.                 this.info.age = value;
  41.                 break
  42.             default:
  43.                 console.log('cannot match in any handlers');
  44.         }
  45.     }
  46. }
  47.  
  48. let info = {
  49.     name: 'Punn',
  50.     age: 22,
  51.     hobbies: [
  52.         'play games',
  53.         'read books'
  54.     ]
  55. };
  56.  
  57. let handlerMapping = {
  58.     'hobbies': HobbiesHandler,
  59.     'age': AgeHandler
  60. }
  61.  
  62. function changeInfo(info, handlerName, action, value) {
  63.     let handlerClass = new (handlerMapping[handlerName] || HandlerBase)(info);
  64.    
  65.     handlerClass.handler(action, value);
  66.     console.log(info)
  67. }
  68.  
  69. changeInfo(info, '', 'addHobby', 'sing songs');
  70. changeInfo(info, 'hobbies', 'addHobby', 'sing songs');
  71. changeInfo(info, 'age', 'changeAge', 23);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement