Advertisement
informaticage

Javascript OOP Excercise

Nov 13th, 2022
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Common array elements
  2. // https://www.codewars.com/kata/5a6225e5d8e145b540000127
  3. class MultiSet {
  4.     constructor(arr = []) {
  5.         this.dataSet = {};
  6.         for (let item of arr) {
  7.             this.addItem(item);
  8.         }
  9.     }
  10.  
  11.     setItem(item, quantity = 1) {
  12.         this.dataSet[item] = quantity;
  13.     }
  14.  
  15.     addItem(item) {
  16.         if (this.dataSet[item])
  17.             this.dataSet[item]++;
  18.         else
  19.             this.dataSet[item] = 1;
  20.     }
  21.  
  22.     getItem(item) {
  23.         return this.dataSet[item] || 0;
  24.     }
  25. }
  26. function common(arr1, arr2, arr3) {
  27.     // Associamo un multiset ad ogni array
  28.     const [ms1, ms2, ms3] = [
  29.         new MultiSet(arr1),
  30.         new MultiSet(arr2),
  31.         new MultiSet(arr3),
  32.     ];
  33.  
  34.     // Uniamo gli elementi in un unico array
  35.     const merged = [...arr1, ...arr2, ...arr3];
  36.  
  37.     // Troviamo gli elementi in comune in tutti e 3 gli array
  38.     const common = new MultiSet();
  39.     for (let item of merged) {
  40.         common.setItem(
  41.             item,
  42.             Math.min(
  43.                 ms1.getItem(
  44.                     item),
  45.                 ms2.getItem(item),
  46.                 ms3.getItem(item),
  47.             )
  48.         )
  49.     }
  50.    
  51.     // Somma degli elementi
  52.     // Presenti sia in arr1 che in arr2 che in arr3
  53.     let sum = 0;
  54.     for (let [item, quantity] of Object.entries(common.dataSet)) {
  55.         sum += item * quantity;
  56.     }
  57.  
  58.     return sum;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement