Skip to content

Instantly share code, notes, and snippets.

@scogle
Created October 7, 2014 16:30
Embed
What would you like to do?
New and improved method to convert recursive structure to the flare format
function toFlareRecursive(options) {
// data: object,
// parentKey: string,
// childKey: string,
// sizeKey: (optional) string or function,
// nameKey: string or function,
// rootName: (optional) string (only used if there's more than one top-level object)
// Return either the value of the name key or the result
// of the nameKey function
function getName(d) {
if ( typeof options.nameKey == "string" ) {
var name = d[options.nameKey];
} else if ( typeof options.nameKey == "function" ) {
var name = options.nameKey(d);
} else {
console.error("Unrecognized nameKey. Must be string or function.")
}
return name;
}
// Return either the value of the size key or the result
// of the sizeKey function
function getSize(d) {
if ( typeof options.sizeKey == "string" ) {
var size = d[options.sizeKey];
} else if ( typeof options.sizeKey == "function" ) {
var size = options.sizeKey(d);
} else {
console.error("Unrecognized sizeKey. Must be string or function.")
}
return size;
}
// Find the children and construct the flare objects
function findChildren(d){
var children = _.filter(options.data, function(obj){
return obj[options.parentKey] === d[options.childKey];
});
if ( children.length > 0 ) {
d.children = [];
_.each(children, function(obj){
obj.name = getName(d);
if ( 'sizeKey' in options ) { obj.size = getSize(obj); }
d.children.push(obj);
findChildren(obj);
});
}
}
// Find the top level of nodes (one or more)
var topLevelNodes = _.filter(options.data, function(obj){
return obj[options.parentKey] === "None";
});
// We need to handle things a little differently depending
// on the number of top-level nodes
if ( topLevelNodes.length === 1 ) {
var root = topLevelNodes[0];
root.name = getName(root);
if ( 'sizeKey' in options ) { root.size = getSize(root); }
}
else if ( topLevelNodes.length === 0 ) {
console.error("Not a tree.");
}
else {
var root = { 'name': options.rootName, 'children':[] };
_.each(topLevelNodes, function(obj){
obj.name = getName(obj);
if ( 'sizeKey' in options ) { obj.size = getSize(obj); }
root.children.push(obj);
findChildren(obj);
});
}
return root;
}
// Usage
var root = toFlareRecursive({
data: json,
parentKey: 'superClass',
childKey: 'thisClass',
rootName: "Classes",
sizeKey: "instances",
nameKey: function(obj){
var prefix = obj['thisClass'].match(/\/([a-zA-Z_]*)\#/)[1],
name = obj['thisClass'].match(/\#(.*)>/)[1];
return prefix + ":" + name;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment