Sunday, 28 December 2014

Generate trees from materialized paths in Jade

Suppose you have the following objects retrieved from a database, in an array. How would you generate a tree in HTML?


name: VEHICLES
path: ,

name: LAND
path: ,VEHICLES,

name: WATER
path: ,VEHICLES,

name: CARS
path: ,VEHICLES,LAND,

name: BICYCLES
path: ,VEHICLES,LAND,

First up is to sort them by path+name:
VEHICLES
LAND
BICYCLES
CARS
WATER

Then, you can recursively (well, not strictly in the sense of that word because of the i, but you get the point) generate the tree using a mixin:

mixin rpt(base)
    - item = items[i];
    - re = new RegExp('^' + base);
    - here = item.path.replace(re, '');
    - here = here.substring(0, here.indexOf(','));
    - re2 = new RegExp('^' + base);
    if here == ''
        li= item.name
        - i++;
    else if re2.test(item.path)
        ol
        mixin rpt(base + here + ',')

ol
     - var i = 0
     while i < items.length
        mixin rpt(',')


Edit: Oh dear pasted the wrong code. Here's the correct one.

            mixin rpt(base)
                - var re = new RegExp('^' + base + '$');
                - var re2 = new RegExp('^' + base);
                - var end = false;
                - while (i < items.length && !end)
                    - var item = items[i];
                    if re.test(item.path)
                        li= item.name
                        - i++;
                    else if re2.test(item.path)
                        ol
                            mixin rpt(item.path)
                    else
                        - end = true
            h1 Areas
            ol
                if items
                    - var i = 0
                    mixin rpt(',')



That was fun!

No comments:

Post a Comment