Visualize a tree: Difference between revisions
→JS Plain text: Updated the decorated-outline version with an option to prune out nodeless lines
m (→Python :: Functional composition: (edited a comment line)) |
(→JS Plain text: Updated the decorated-outline version with an option to prune out nodeless lines) |
||
Line 1,297:
===Plain text===
====Decorated outline====
<lang JavaScript>(() => {
'use strict';
// drawTree :: Bool -> Tree String -> String
const drawTree = blnCompact => tree => {
// Simple decorated-outline style of ascii tree drawing,
// with nodeless lines pruned out if blnCompact is True.
const xs = draw(tree);
return unlines(
blnCompact ? (
xs.filter(
s => s.split('')
.some(c => !' │'.includes(c))
)
) : xs
);
};
// draw :: Tree String -> [String]
Line 1,331 ⟶ 1,344:
};
// TEST -----------------------------------------------
const
'Alpha', [
Node('Beta', [
Node('Epsilon', []),
Node('Zeta', []),
Node('Eta', [])
]),
Node('Gamma', [Node('Theta', [])]),
Node('Delta', [
Node('Iota', []),
Node('Kappa', []),
Node('Lambda', [])
])
]);
return [true, false]
.map(blnCompact => drawTree(blnCompact)(tree))
};
// GENERIC FUNCTIONS ----------------------------------
// Node :: a -> [Tree a] -> Tree a
const Node = (v, xs) => ({
type: 'Node',
root: v, // any type of value (consistent across tree)
nest: xs || []
});
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = (xs, ys) => xs.concat(ys);
// chars :: String -> [Char]
const chars = s => s.split('');
// cons :: a -> [a] -> [a]
const cons = (x, xs) => [x].concat(xs);
// Returns Infinity over objects without finite length.
//
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// lines :: String -> [String]
Line 1,434 ⟶ 1,404:
length: n
}, () => x);
// take :: Int -> [a] -> [a]
const take = (n, xs) =>
xs.slice(0, n);
// unlines :: [String] -> String
Line 1,473 ⟶ 1,427:
// MAIN ---
})();</lang>
{{Out}}
<pre>
├─ Beta
│ ├─ Epsilon
│ ├─ Zeta
│ └─ Eta
├─ Gamma
│ └─ Theta
└─ Delta
├─ Iota
├─ Kappa
└─ Lambda
Alpha
│
├─
│ │
│ ├─
│ │
│ ├─
│ │
│ └─
│
├─
│ │
│ └─
│
└─
│
├─ Iota
│
├─ Kappa
│
└─ Lambda</pre>
=={{header|Julia}}==
|