Created
August 9, 2017 06:31
-
-
Save s-melnikov/d1038c82e275244a2b6b122b5d041bf8 to your computer and use it in GitHub Desktop.
Nested sets
This file contains hidden or 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
var data = [ | |
{ | |
title: "Одежда", | |
left: 1, | |
right: 22 | |
}, | |
{ | |
title: "Мужская", | |
left: 2, | |
right: 9 | |
}, | |
{ | |
title: "Женская", | |
left: 10, | |
right: 21 | |
}, | |
{ | |
title: "Костюмы", | |
left: 3, | |
right: 8 | |
}, | |
{ | |
title: "Платья", | |
left: 11, | |
right: 16 | |
}, | |
{ | |
title: "Юбки", | |
left: 17, | |
right: 18 | |
}, | |
{ | |
title: "Блузы", | |
left: 19, | |
right: 20 | |
}, | |
{ | |
title: "Брюки", | |
left: 4, | |
right: 5 | |
}, | |
{ | |
title: "Жакеты", | |
left: 6, | |
right: 7 | |
}, | |
{ | |
title: "Вечерние", | |
left: 12, | |
right: 13 | |
}, | |
{ | |
title: "Летние", | |
left: 14, | |
right: 15 | |
} | |
] | |
const walk = data => { | |
if (!data) return; | |
for (let i = 0; i < data.length; i++) { | |
for (let l = 0; l < data.length; l++) { | |
if (data[l].left > data[i].left && data[l].right < data[i].right) { | |
data[i].children = data[i].children || [] | |
data[i].children.push(data.splice(l, 1)[0]) | |
l-- | |
} | |
} | |
delete data[i].left | |
delete data[i].right | |
walk(data[i].children) | |
} | |
return data | |
} | |
let tree = walk(data) | |
const flatty = (tree, counter) => { | |
let result = [] | |
counter = counter || { index: 1 } | |
for (let i = 0; i < tree.length; i++) { | |
result.push(tree[i]) | |
tree[i].left = counter.index++ | |
if (tree[i].children) { | |
result = result.concat(flatty(tree[i].children, counter)) | |
delete tree[i].children | |
} | |
tree[i].right = counter.index++ | |
} | |
return result | |
} | |
let flat = flatty(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment