Skip to content

Instantly share code, notes, and snippets.

@thekevinscott
Last active August 15, 2017 05:17
Show Gist options
  • Save thekevinscott/a71fe2c419aaf7edbfad to your computer and use it in GitHub Desktop.
Save thekevinscott/a71fe2c419aaf7edbfad to your computer and use it in GitHub Desktop.
explodeTree in Javascript
// Function for exploding an array of strings representing files on disk into a tree structure.
// Takes something like this
var files = [
'debug.js',
'users/create.js',
'users/edit.js',
'users/list/a.js',
'users/list/b.js'];
// and turns it into this
var expectedObj = {
'debug': 'debug',
'users': {
'create': 'create',
'edit': 'edit',
'list': {
'a': 'a',
'b': 'b'
}
}
};
function explodeTree(files, delimiter) {
function getType(obj) {
var type = Object.prototype.toString.call(obj);
if (type.indexOf('Array') !== -1) {
return 'array';
} else if (type.indexOf('String') !== -1) {
return 'string';
} else if (type.indexOf('Undefined') !== -1) {
return 'undefined';
} else {
return 'unknown';
}
}
var obj = {};
if (!delimiter) {delimiter = '/';}
files.map(function (file) {
var file = file.split('.').shift();
var paths = file.split(delimiter);
if (paths.length > 1) {
var key = paths.shift();
} else {
var key = paths[0];
}
switch (getType(obj[key])) {
case 'undefined':
obj[key] = paths.join(delimiter);
break;
case 'string':
obj[key] = [obj[key], paths.join(delimiter)];
break;
case 'array':
obj[key].push(paths.join(delimiter));
break;
}
});
for (var key in obj) {
var val = obj[key];
switch (getType(val)) {
case 'array':
obj[key] = explodeTree(val, delimiter);
break;
}
}
return obj;
};
// Test that the function works, relying on Underscore
var obj = explodeTree(files);
if (!_.isEqual(obj, expectedObj)) {
console.log('FAIL', obj);
} else {
console.log('PASS');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment