SmaJli

intersectionDeep

Mar 11th, 2022
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  //   13. Write a method that finds deep intersections of objects
  2.       const obj1 = { a: 1, b: { c: 3 } };
  3.       const obj2 = { b: { c: 3 }, d: 4 };
  4.  
  5.       function intersectionDeep(obj1, obj2) {
  6.         // {c : 3} {c : 3}
  7.         function isDeepEqual(v1, v2) {
  8.  
  9.  
  10.         // return JSON.stringify(v1) === JSON.stringify(v2)
  11.  
  12.           if (v1 === v2) {
  13.             return true;
  14.           }
  15.           // ocekuvame objects
  16.           if (
  17.             v1 === null ||
  18.             v2 === null ||
  19.             typeof v1 !== "object" ||
  20.             typeof v2 !== "object"
  21.           ) {
  22.             return false;
  23.           }
  24.  
  25.           let v1k = Object.keys(v1);
  26.           let v2k = Object.keys(v2);
  27.  
  28.           // ako ima ralizcen broj na props
  29.           if (v1k.length !== v2k.length) {
  30.             return false;
  31.           }
  32.  
  33.           // c
  34.           for (const prop of v1k) {
  35.             if (!v2k.includes(prop) || !isDeepEqual(v1[prop], v2[prop])) {
  36.               return false;
  37.             }
  38.           }
  39.  
  40.           return JSON.stringify(value1) === JSON.stringify(value2);
  41.         }
  42.         const output = {};
  43.         const keys1 = Object.keys(obj1);
  44.         const keys2 = Object.keys(obj2);
  45.        
  46.  
  47.         // zaednicki elementi od dve nizi
  48.  
  49.         const intersectionKeys = keys1.filter((key1) => keys2.includes(key1));
  50.         // console.log({ intersectionKeys })["b"];
  51.  
  52.         for (const prop of intersectionKeys) {
  53.           if (isDeepEqual(keys1[prop], keys2[prop])) {
  54.             output[prop] = keys1[prop];
  55.           }
  56.         }
  57.         console.log({ output });
  58.         return output;
  59.       }
  60.       intersectionDeep(obj1, obj2); // -> {b: {c : 3}}
  61.  
  62.       const ob1 = { a: 1, b: { c: { d: 5 } } };
  63.       const ob2 = { b: { c: { d: 5 } }, d: 4 };
  64.       function intersectionDeep(ob1, ob2) {
  65.         var newObj = {};
  66.         for (var key in ob1) {
  67.           if (typeof ob1[key] === "object") {
  68.             var obj = intersectionDeep(ob1[key], ob2[key]);
  69.             newObj[key] = obj;
  70.           } else if (ob1[key] === ob2[key]) {
  71.             newObj[key] = ob1[key];
  72.           }
  73.         }
  74.         return newObj;
  75.       }
  76.       function isObject(object) {
  77.         return object != null && typeof object === "object";
  78.       }
  79.       console.log(intersectionDeep(ob1, ob2));
Advertisement
Add Comment
Please, Sign In to add comment