Advertisement
Thenlie

Untitled

Dec 7th, 2022
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const data = fs.readFileSync('input.txt', 'utf8');
  3. const data_array = data.split('\n');
  4.  
  5. let stack = [];
  6. let total = [];
  7.  
  8. const command_handler = (words) => {
  9.     if (words[1] === 'cd') {
  10.         if (words[2] === '..') {
  11.             stack.pop();
  12.         } else {
  13.             stack.push({name: words[2], size: 0});
  14.             const index = total.map(x => x.name).indexOf(words[2]);
  15.             if (index === -1) total.push({name: words[2], size: 0});
  16.         }
  17.     }
  18. }
  19.  
  20. const file_handler = (words) => {
  21.     for (let i = 0; i < stack.length; i++) {
  22.         const index = total.map(x => x.name).indexOf(stack[i].name);
  23.         total[index].size += parseInt(words[0]);
  24.     }
  25. }
  26.  
  27. data_array.forEach(line => {
  28.     const words = line.split(' ');
  29.     if (words[0] === '$') command_handler(words);
  30.     else if (words[0] !== 'dir') file_handler(words);
  31. });
  32.  
  33. console.table(total)
  34. const answer = total.filter(x => x.size <= 100000);
  35. console.table(answer)
  36. let sum = 0;
  37. answer.forEach(ans => sum += ans.size)
  38. console.log(sum);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement