Skip to content

Instantly share code, notes, and snippets.

@allestaire
Last active August 4, 2022 13:19
Show Gist options
  • Save allestaire/a8a0ac26d6ea544fe1926338ba11ca2d to your computer and use it in GitHub Desktop.
Save allestaire/a8a0ac26d6ea544fe1926338ba11ca2d to your computer and use it in GitHub Desktop.
const items = [
{ id: 2, seqId: 4, parent: 5, name: "index.tsx" },
{ id: 3, seqId: 3, parent: 1, name: "Sidebar" },
{ id: 4, seqId: 5, parent: 1, name: "Table" },
{ id: 7, seqId: 5, parent: 5, name: "SelectableDropdown.tsx" },
{ id: 5, seqId: 2, parent: 1, name: "AssignmentTable" },
{ id: 1, seqId: 1, parent: null, name: "components" },
{ id: 6, seqId: 2, parent: null, name: "controllers" },
{ id: 8, seqId: 8, parent: 3, name: "controllers" },
]
function transformItems(items, i=0, sorted=false) {
const next = i+1
const tmp = items[i]
const newData = items[next] || null
if(sorted) {
// break recursion when index of array is out of bound
if(!Boolean(items[i])) {
return items
}
// Initialize depth value
tmp.depth = Boolean(tmp.depth) ?tmp.depth :0
let stillChecking = true
// Let loop untill we know
// there are no matching items
while(stillChecking) {
let mustCheck = false;
// Loop in reserve order
// So that everytime the item is added
// it will be on ascending order
for(let x=items.length; x--;) {
const item = items[x]
// Lets skip current item and
// items that already has depth
if(item.id == tmp.id || Boolean(item.depth)) {
continue;
}
if(Boolean(item.parent) && item.parent == tmp.id) {
// What 2 items
// And place it under its parent
const toTransfer = items.splice(x,1)[0]
toTransfer.depth = tmp.depth+1
items.splice(i+1, 0, toTransfer)
mustCheck = true
}
}
// Are there still checking?
if(!mustCheck) {
stillChecking = false
}
}
return transformItems(items, i+1, true)
} else {
// swap data when current seq id is more than to its next item
if(newData) {
if(tmp.seqId > newData.seqId) {
items[i] = newData
items[next] = tmp
}
}
let notSorted = false;
// Lets check if all are all sorted
for(let x=0; x < items.length; x++) {
if(Boolean(items[x+1])) {
if(items[x].seqId > items[x+1].seqId) {
notSorted = true;
break;
}
}
}
if(notSorted) {
// Continue sorted
return transformItems(items, items.length-1 == i ?0 :i+1);
} else {
// Manage depth
return transformItems(items, 0, true);
}
}
return items
}
const finalItems = transformItems(items);
console.log(finalItems)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment