Created
August 1, 2015 21:27
-
-
Save maximzasorin/5d243c60ee60e8f1bf0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Task 3</title> | |
<style> | |
textarea { width: 400px; height: 200px; } | |
</style> | |
</head> | |
<body> | |
<div> | |
<h2>Source</h2> | |
<textarea id="source">[ | |
{id: 1, parentId: 0}, | |
{id: 2, parentId: 0}, | |
{id: 3, parentId: 1}, | |
{id: 4, parentId: 1}, | |
{id: 5, parentId: 2}, | |
{id: 6, parentId: 4}, | |
{id: 7, parentId: 5} | |
];</textarea> | |
</div> | |
<div style="margin-top: 20px;"> | |
<button id="runButton">Process</button> | |
</div> | |
<div> | |
<h2>Result</h2> | |
<textarea id="dest"></textarea> | |
</div> | |
<script src="js/plain-to-tree.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
function findChild(array, parentId) { | |
for (var i = 0; i < array.length; i++) { | |
if (array[i].parentId == parentId) { | |
var child = array[i]; | |
array.splice(i, 1); | |
return child; | |
} | |
} | |
return null; | |
} | |
function makeTreeRecursive(element, array, id) { | |
while (child = findChild(array, id)) { | |
if (!('children' in element)) { | |
element.children = []; | |
} | |
element.children.push(child); | |
makeTreeRecursive(child, array, child.id); | |
} | |
return element.children; | |
} | |
function makeTree(array, id) { | |
return makeTreeRecursive({children: []}, array.slice(), 0); | |
} | |
function makeTreeFromArray() { | |
var sourceTextarea = document.getElementById('source'); | |
var destTextarea = document.getElementById('dest'); | |
var source = eval(sourceTextarea.value); | |
// run recursive | |
var tree = makeTree(source); | |
destTextarea.value = JSON.stringify(tree, "", 4); | |
} | |
makeTreeFromArray(); | |
// events | |
document.getElementById('runButton').onclick = makeTreeFromArray; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment