Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created July 4, 2020 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RStankov/a10173768b154acce238fa9b04b41163 to your computer and use it in GitHub Desktop.
Save RStankov/a10173768b154acce238fa9b04b41163 to your computer and use it in GitHub Desktop.
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