feeles-ide
Version:
The hackable and serializable IDE to make learning material
31 lines (28 loc) • 849 B
JavaScript
/**
* @param items Array of files
* @param path A string of current path like 'sub/' (default='')
* @param An object has hierarchy
*/
export default function getHierarchy(items) {
var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var files = [];
var dirs = [];
items.filter(function (item) {
return item.name.indexOf(path) === 0;
}).forEach(function (item, i, all) {
var relativePath = item.name.replace(path, '');
var slash = relativePath.indexOf('/');
if (slash < 0) {
// no slash
files.push(item);
return;
}
var subPath = path + relativePath.substr(0, slash + 1);
if (dirs.every(function (dir) {
return dir.path !== subPath;
})) {
dirs.push(getHierarchy(all, subPath));
}
});
return { files: files, dirs: dirs, path: path };
}