Last active
August 13, 2020 10:22
-
-
Save PetarKirov/4390954a8d4edc09b5b74e17ebd6551c to your computer and use it in GitHub Desktop.
tree formatting
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
void main() | |
{ | |
import std.json : parseJSON; | |
import std.stdio : writeln; | |
const parsed = mySampleJson.parseJSON; | |
const tree = parsed.jsonToTree; | |
(*tree).writeln; | |
} | |
struct Tree(T) | |
{ | |
T elem; | |
Tree!T*[] children; | |
void toString(W)(auto ref W writer) const | |
{ | |
toStringImpl(writer, &this, null); | |
} | |
static void toStringImpl | |
(W) | |
(auto ref W writer, in Tree!T* x, string prefix) | |
{ | |
import std.conv : to; | |
import std.range.primitives : put; | |
put(writer, x.elem.to!string); | |
foreach (idx, value; x.children) | |
{ | |
const isLast = idx == x.children.length - 1; | |
put(writer, "\n" ~ prefix ~ (isLast ? "└── " : "├── ")); | |
toStringImpl(writer, value, prefix ~ (isLast ? " " : "│ ")); | |
} | |
} | |
} | |
Tree!string* jsonToTree(J)(J json) | |
{ | |
import std.array : array; | |
import std.algorithm : map; | |
import std.json : JSONType; | |
if (json.type != JSONType.object) | |
return null; | |
Tree!string*[] children; | |
if ("children" in json.object && json.object["children"].type == JSONType.array) | |
children = json.object["children"] | |
.array | |
.map!(json => jsonToTree(json)) | |
.array; | |
return new Tree!string | |
( | |
json.object["name"].str, | |
children | |
); | |
} | |
const mySampleJson = ` | |
{ | |
"name": "my-project", | |
"children": | |
[ | |
{ | |
"name": "node_modules", | |
"children": | |
[ | |
{ | |
"name": "react", | |
"children": | |
[ | |
{ | |
"name": "docs", | |
"children": | |
[ | |
] | |
}, | |
{ | |
"name": "node_modules", | |
"children": | |
[ | |
{ | |
"name": "webpack", | |
"children": | |
[ | |
{ | |
"name": "docs", | |
"children": | |
[ | |
] | |
}, | |
{ | |
"name": "src", | |
"children": | |
[ | |
{ | |
"name": "index.js" | |
} | |
] | |
} | |
] | |
}, | |
] | |
}, | |
{ | |
"name": "src", | |
"children": | |
[ | |
{ | |
"name": "index.js" | |
}, | |
{ | |
"name": "react", | |
"children": | |
[ | |
{ | |
"name": "tree.js" | |
}, | |
] | |
}, | |
] | |
}, | |
] | |
}, | |
] | |
}, | |
{ | |
"name": "src", | |
"children": | |
[ | |
{ | |
"name": "index.js" | |
} | |
] | |
}, | |
] | |
}`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment