Skip to content

Instantly share code, notes, and snippets.

@dmitry-izmerov
Last active June 21, 2016 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitry-izmerov/2f481edd34d86aa533e36a21d3055d67 to your computer and use it in GitHub Desktop.
Save dmitry-izmerov/2f481edd34d86aa533e36a21d3055d67 to your computer and use it in GitHub Desktop.
Build object tree on array of strings with hierarchy of roles and getting of leaves from this tree.
var data = [
'all', 'all/staff', 'all/staff/developer', 'all/staff/manager', 'all/staff/engineer',
'all', 'all/other', 'all/other/writer', 'all/other/hr'
];
var delimeter = '/';
function getStructure(data) {
var structure = {
isLeave: true
};
data.forEach(function(s) {
builder(structure, s.split(delimeter));
})
return structure;
}
function builder(struct, item) {
if (!item.length) return;
var name = item.splice(0, 1);
if (!struct[name]) {
struct.isLeave = false;
struct[name] = {
isLeave: true
};
}
builder(struct[name], item);
}
function getLeaves(struct, name, leaves) {
if (struct.isLeave) {
leaves.push(name);
return;
}
for (p in struct) {
if (p == 'isLeave') {
continue;
}
getLeaves(struct[p], (name ? name + delimeter + p : p), leaves);
}
}
var leaves = [];
getLeaves(getStructure(data), '', leaves)
console.log(leaves);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment