Last active
June 21, 2016 20:13
-
-
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.
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
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