Created
November 15, 2020 03:59
-
-
Save exbotanical/7d23da20d675e7cb50aa5a1fdc5dc5c1 to your computer and use it in GitHub Desktop.
Messing around
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
/* auxillary helpers */ | |
const setPermissions = (r, w, x) => ({ | |
read: r || false, | |
write: w || false, | |
execute: x || false, | |
}); | |
const permissionsEnum = { | |
read: "r", | |
write: "w", | |
execute: "x", | |
none: "-" | |
}; | |
const fPerms = ({ owner, group, others }) => { | |
const permStr = []; | |
const collatePerms = (...args) => { | |
for (const item of args) { | |
for (const prop in item) { | |
permStr.push(item[prop] ? permissionsEnum[prop] : permissionsEnum["none"]); | |
} | |
} | |
}; | |
collatePerms(owner, group, others); | |
return permStr.join(""); | |
}; | |
const rootCtx = "ROOT"; | |
/* fs classes */ | |
class File { | |
constructor(name, parent, group, owner) { | |
this.name = name; | |
this.parent = parent || rootCtx; | |
this.group = group || "root"; | |
this.owner = owner || "root"; | |
this.permissions = { | |
owner: setPermissions(true, true, false), | |
group: setPermissions(true, true, false), | |
others: setPermissions(true, false, false) | |
} | |
this.created = new Date().toDateString().slice(4, 10); | |
} | |
resetCtx (parent) { | |
this.parent = rootCtx; | |
} | |
chmod(type, read, write, execute) { | |
this.permissions[type] = setPermissions(read, write, execute); | |
} | |
} | |
class Directory extends File { | |
constructor(name, parent) { | |
super(name, parent); | |
this.files = []; | |
} | |
add (file) { | |
file.parent = this.name; | |
this.files.push(file); | |
return this; | |
} | |
ls (flags) { | |
switch(flags) { | |
case "-l": | |
for (let file of this.files) { | |
console.log( | |
fPerms(file.permissions), | |
file.group, | |
file.owner, | |
file.created, | |
file.name | |
); | |
} | |
break; | |
default: | |
for (let file of this.files) { | |
console.log(file.name); | |
} | |
break; | |
} | |
} | |
rm (filename) { | |
const idx = this.files.findIndex(file => file.name === filename); | |
if (idx !== -1) { | |
this.files[idx].resetCtx(); | |
this.files.splice(idx, 1); | |
} | |
return this; | |
} | |
touch (filename) { | |
const f = new File(filename, this.name); | |
this.files.push(f); | |
return this; | |
} | |
} | |
/* demo */ | |
const f = new File("hello.txt"); | |
const d = new Directory("notes"); | |
d.add(f).ls("-l"); | |
f.chmod("group", true, true, true); | |
d.touch("man.txt").ls("-l"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment