Skip to content

Instantly share code, notes, and snippets.

@azproduction
Forked from 140bytes/LICENSE.txt
Created December 19, 2011 08:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azproduction/1496110 to your computer and use it in GitHub Desktop.
Save azproduction/1496110 to your computer and use it in GitHub Desktop.
File system tree builder - 119 bytes

File system tree builder

  1. all paths must be absolute
  2. last item in path is file
var input = ['/a/b/.git/config', '/a/x/d/x.js', '/a/x/d/x/ololo.xml'];

var output = {
  "#": {
    "a": {
      "x": {
        "d": {
          "x": {
            "ololo.xml": "ololo.xml"
          },
          "x.js": "x.js"
        }
      },
      "b": {
        ".git": {
          "config": "config"
        }
      }
    }
  }
}

demo: http://jsfiddle.net/bnhyF/

function (
paths, // {String[]} list of absolute paths
parts, // path parts
target, // pointer to current subtree
file, // path item
fs // result fs tree
) {
// init fs, reset pointer, get item
for (fs = {};target = fs,parts = paths.pop();) {
parts = ('#' + parts).split('/'); // split path
while (parts[0]) { // while !eopath
target = target[file = parts.shift()] // set current pointer to file
= parts[0] ? target[file] || {} // !last -> its a dir
: file; // else -> file
}
}
return fs;
}
function(a,b,c,d,e){for(e={};c=e,b=a.pop();){b=("#"+b).split("/");while(b[0])c=c[d=b.shift()]=b[0]?c[d]||{}:d}return e}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mikhail Davydov
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "fs_tree",
"description": "File system tree builder",
"keywords": [
"fs"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>{"#":{"a":{"x":{"d":{"x":{"ololo.xml":"ololo.xml"},"x.js":"x.js"}},"b":{".git":{"config":"config"}}}}}</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var fs_tree = function(a,b,c,d,e){for(e={};c=e,b=a.pop();){b=("#"+b).split("/");while(b[0])c=c[d=b.shift()]=b[0]?c[d]||{}:d}return e};
var paths = ['/a/b/.git/config/', '/a/x/d/x.js', '/a/x/d/x/ololo.xml'];
document.getElementById('ret').innerHTML = JSON.stringify(fs_tree(paths));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment