Created
July 4, 2020 14:39
-
-
Save RStankov/a10173768b154acce238fa9b04b41163 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
function buildNode(todo) { | |
return { | |
todo, | |
children: [], | |
}; | |
} | |
function buildTree(todos) { | |
const root = buildNode(); | |
let stack = [root]; | |
for (let i = 0; i < todos.length; i += 1) { | |
const todo = todos[i]; | |
if (!stack[todo.ident]) { | |
// NOTE(rstankov): THIS CASE DOESN'T WORK! | |
// maybe add a lot of empty trees | |
// have this into the sorting | |
stack[todo.ident] = buildNode(); | |
} | |
node = buildNode(todo); | |
stack[todo.ident].children.push(node); | |
stack = stack.slice(0, todo.ident + 1); | |
stack[todo.ident + 1] = node; | |
} | |
return root; | |
} | |
function sortTree(node) { | |
// TODO(rstankov): Sort three leaves based on the `isCompleted` | |
return node; | |
} | |
function treeToArray(node, acc = []) { | |
if (node.todo) { | |
acc.push(node.todo); | |
} | |
return node.children.reduce((a, n) => treeToArray(n, a), acc); | |
} | |
todos = [ | |
{ | |
text: '1', | |
ident: 0, | |
isCompleted: false, | |
}, | |
{ | |
text: '1-1', | |
ident: 1, | |
isCompleted: false, | |
}, | |
{ | |
text: '1-1-1', | |
ident: 2, | |
isCompleted: false, | |
}, | |
{ | |
text: '1-1-2', | |
ident: 2, | |
isCompleted: false, | |
}, | |
{ | |
text: '1-1-----n', | |
ident: 10, | |
isCompleted: false, | |
}, | |
{ | |
text: '1-1-3', | |
ident: 2, | |
isCompleted: true, | |
}, | |
{ | |
text: '1-2', | |
ident: 1, | |
isCompleted: false, | |
}, | |
{ | |
text: '2', | |
ident: 0, | |
isCompleted: true, | |
}, | |
{ | |
text: '3', | |
ident: 0, | |
isCompleted: true, | |
}, | |
]; | |
sortedArray = treeToArray(sortTree(buildTree(todos))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment