Created
May 25, 2021 01:43
-
-
Save khtdr/d336d2a5dde1a9ebf8b24202bb448955 to your computer and use it in GitHub Desktop.
This file contains 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
class FS { | |
root = { | |
type:'directory', | |
name:'/', | |
children:[], | |
} | |
sort(node) { | |
node.children.sort((a, b) => { | |
if (a.type == b.type) return a.name.localeCompare(b.name); | |
if (a.type === 'directory') return -1; | |
return 1; | |
}) | |
} | |
mkdir(path) { | |
let cwd = this.root; | |
const dirs = path.substr(1).split('/'); | |
dirs.forEach(name => { | |
const dir = cwd.children.filter(child => ( | |
child.name == name | |
)).shift(); | |
if (!dir) { | |
const next_cwd = { type:'directory', name, children:[]}; | |
cwd.children.push(next_cwd); | |
this.sort(cwd); | |
cwd = next_cwd; | |
} else cwd = dir; | |
}) | |
return cwd; | |
} | |
mkfile(path) { | |
const parts = path.split('/'); | |
const name = parts.pop(); | |
const dir = parts.join('/'); | |
const cwd = this.mkdir(dir); | |
const file = { type: 'file', name }; | |
cwd.children.push(file); | |
this.sort(cwd); | |
} | |
add(path) { | |
const parts = path.split('/'); | |
const last = parts.pop(); | |
if (last.indexOf('.') >= 0) this.mkfile(path) | |
else this.mkdir(path) | |
} | |
constructor(paths) { paths.map(path => this.add(path)) } | |
} | |
const fs = new FS([ | |
'/path/to/something.txt', | |
'/path/to', | |
'/path/to/anything.txt', | |
'/path/to/some/deep/file.txt', | |
'/another/path/to/some/file.txt', | |
]); | |
console.log(JSON.stringify(fs.root, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment