data-traversal
Version:
a tool for tree data traversing
153 lines (134 loc) • 3.54 kB
HTML
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>test traversal</title>
<style>
p {
white-space: nowrap;
overflow: hidden;
}
h1 {
text-align: center;
position: absolute;
padding: 0 10px;
top: 50%;
left: 0;
transform: translateY(-50%);
}
span {
color: #f00;
text-transform: uppercase;
}
</style>
</head>
<body>
<p>......hello world..................................</p>
<h1>open <span>console</span> to see the result</h1>
<script src="../traversal.js"></script>
<script>
var data = [{
id: '1',
children: [{
id: '2',
children: [{
id: '4'
},
{
id: '5',
children: [{
id: '8'
}]
}]
},
{
id: '3',
children: [{
id: '6'
},
{
id: '7',
children: [{
id: '9',
children: [{
id: '10'
},
{
id: '11'
}]
}]
}]
}]
}];
console.log('breadth');
(function () {
console.log('normal');
var result = '';
traversal.breadth(data, function (obj) {
result += obj.id + ' ';
});
console.log(result);
})();
(function () {
console.log('break');
var result = '';
traversal.breadth(data, function (obj, res, e) {
result += obj.id + ' ';
if (obj.id === '8') {
e.break = true;
}
});
console.log(result);
})();
(function () {
console.log('return');
var result = traversal.breadth(data, function (obj, res, e) {
if (obj.id === '8') {
e.break = true;
}
else {
res += obj.id + ' ';
}
return res;
}, '');
console.log(result);
})();
console.log(' ');
console.log('depth');
(function () {
console.log('normal');
var result = '';
traversal.depth(data, function (obj) {
result += obj.id + ' ';
});
console.log(result);
})();
(function () {
console.log('break');
var result = '';
traversal.depth(data, function (obj, res, e) {
result += obj.id + ' ';
if (obj.id === '8') {
e.break = true;
}
});
console.log(result);
})();
(function () {
console.log('return');
var result = traversal.depth(data, function (obj, res, e) {
if (obj.id === '8') {
e.break = true;
}
else {
res += obj.id + ' ';
}
return res;
}, '');
console.log(result);
})();
</script>
</body>
</html>