Created
October 6, 2020 03:00
-
-
Save charlieInDen/901b3c57452107a8fdba9ccc5f1c5628 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 FileSystem { | |
class File { | |
var isFile = false | |
var files: [String: File] = [String: File]() | |
var content = "" | |
} | |
var root: File! | |
init() { | |
root = File() | |
} | |
func ls(_ path: String) -> [String] { | |
var temp: File = root | |
var files: [String] = [] | |
if path != "/" { | |
let d: [String] = path.components(separatedBy: "/") | |
for i in 0..<d.count { | |
if let file = temp.files[d[i]] { | |
temp = file | |
} | |
} | |
if temp.isFile, let last = d.last { | |
files.append(last) | |
return files | |
} | |
} | |
var result = temp.files.keys.sorted() | |
return result | |
} | |
func mkdir(_ path: String) { | |
var temp: File? = root | |
var d = path.split(separator: "/") | |
for i in 0..<d.count { | |
if temp?.files[String(d[i])] == nil { | |
temp?.files[String(d[i])] = File() | |
} | |
temp = temp?.files[String(d[i])] | |
} | |
} | |
func addContentToFile(_ filePath: String, _ content: String) { | |
var temp: File? = root | |
var d = filePath.split(separator: "/") | |
for i in 0..<d.count - 1 { | |
temp = temp?.files[String(d[i])] | |
} | |
if temp?.files[String(d[d.count - 1])] == nil { | |
temp?.files[String(d[d.count - 1])] = File() | |
} | |
temp = temp?.files[String(d[d.count - 1])] | |
temp?.isFile = true | |
temp?.content = temp!.content + content | |
} | |
func readContentFromFile(_ filePath: String) -> String { | |
var temp: File = root | |
var d = filePath.split(separator: "/") | |
for i in 0..<(d.count - 1) { | |
if let file = temp.files[String(d[i])] { | |
temp = file | |
} | |
} | |
if let last = d.last, let file: File = temp.files[String(last)] { | |
return file.content | |
} | |
return "" | |
} | |
} | |
/** | |
* Your FileSystem object will be instantiated and called as such: | |
* let obj = FileSystem() | |
* let ret_1: [String] = obj.ls(path) | |
* obj.mkdir(path) | |
* obj.addContentToFile(filePath, content) | |
* let ret_4: String = obj.readContentFromFile(filePath) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment