Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. function createImmutable(item){
  2. let handler = {
  3. set: function(target, property, value){
  4. //do nothing, this object is no longer "directly" mutable
  5. console.log("hey, I'm immutable, you can't set me like this");
  6. },
  7.  
  8. //object is mutable only by invoking a "set_XXXX" method
  9. //we trap that get and return a function that will create the new object with the mutated property
  10. //and returns a proxy around the new object, so that immutability continues to work in ensuing assignments
  11. get: function(target, property, receiver){
  12. if (property.startsWith("set_")){
  13. let propName = property.substring(4);
  14. console.log("assigning to " + propName + " via proxy");
  15. return function(value){
  16. //either use the trapped target or "this"
  17. //let newItem = new target.constructor();
  18. let newItem = new this.constructor();
  19. Object.assign(newItem, target);
  20. //notice I've just doing shallow cloning
  21. newItem[propName] = value;
  22. return new Proxy(newItem, handler);
  23. }
  24.  
  25. }
  26. else{
  27. return target[property];
  28. }
  29.  
  30. }
  31. };
  32.  
  33. return new Proxy(item, handler);
  34. }
  35.  
  36. //Let's test it
  37.  
  38. class Person{
  39. constructor(name){
  40. this.name = name;
  41. }
  42.  
  43. say(word){
  44. return `${word}, I'm ${this.name}`;
  45. }
  46. }
  47.  
  48. //--- Main
  49. console.log("started");
  50. let p1 = new Person("Francois");
  51.  
  52. console.log("p1 says: " + p1.say("hi"));
  53.  
  54. let immutableP1 = createImmutable(p1);
  55.  
  56. console.log("immutableP1" + JSON.stringify(immutableP1));
  57. immutableP1.name = "Xuan";
  58. console.log("immutableP1" + JSON.stringify(immutableP1));
  59.  
  60. let immutableP2 = immutableP1.set_name("Xuan");
  61. console.log("immutableP2" + JSON.stringify(immutableP2));
  62.  
  63. console.log(immutableP2.say("hi"));
  64.  
  65. let immutableP3 = immutableP2.set_name("Emmanuel");
  66. console.log("immutableP3" + JSON.stringify(immutableP3));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement