Last active
February 28, 2023 18:05
-
-
Save domanskyi/85222b10c76f1ecbd708d50f106fc668 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input = `$ cd / | |
$ ls | |
dir a | |
14848514 b.txt | |
8504156 c.dat | |
dir d | |
$ cd a | |
$ ls | |
dir e | |
29116 f | |
2557 g | |
62596 h.lst | |
$ cd e | |
$ ls | |
584 i | |
$ cd .. | |
$ cd .. | |
$ cd d | |
$ ls | |
4060174 j | |
8033020 d.log | |
5626152 d.ext | |
7214296 k | |
`; | |
const MAX_FILE_SIZE = 100000; | |
const FOLDERS_PATH_DIVIDER = "."; | |
const moveForward = (currentPath, dirName) => | |
(currentPath += `${FOLDERS_PATH_DIVIDER}${dirName}`); | |
const moveBack = (currentPath) => | |
currentPath.slice(0, -currentPath.lastIndexOf(FOLDERS_PATH_DIVIDER)); | |
const parse = (string) => { | |
const stringArr = string.split("\n"); | |
const resObj = {}; | |
let currentPath = ""; | |
stringArr.map((s) => { | |
if (s.includes("$ cd")) { | |
const dirName = s.split(" ")[2]; | |
currentPath = | |
dirName === ".." | |
? moveBack(currentPath) | |
: moveForward(currentPath, dirName); | |
} else if (!s.includes("$ ls") && !s.includes("dir")) { | |
const fileSize = +s.split(" ")[0]; | |
resObj[currentPath] = resObj[currentPath] + fileSize || fileSize; | |
} | |
}); | |
// not the best solution from the time complexity perspective, but i didn't find any other | |
// I guess it will be better to use the tree instead of flat object with full paths | |
Object.entries(resObj).map(([key, value]) => { | |
let parentFolder = key; | |
while (parentFolder.length > 2) { | |
parentFolder = moveBack(parentFolder); | |
resObj[parentFolder] = resObj[parentFolder] + value; | |
} | |
}); | |
const sumOfFolderSizes = Object.entries(resObj).reduce( | |
(acc, [_, value]) => (value < MAX_FILE_SIZE ? acc + value : acc), | |
0 | |
); | |
return sumOfFolderSizes; | |
}; | |
console.log(parse(input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment