Skip to content

Instantly share code, notes, and snippets.

@PetarKirov
Last active August 13, 2020 10:22
Show Gist options
  • Save PetarKirov/4390954a8d4edc09b5b74e17ebd6551c to your computer and use it in GitHub Desktop.
Save PetarKirov/4390954a8d4edc09b5b74e17ebd6551c to your computer and use it in GitHub Desktop.
tree formatting
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