Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created September 27, 2017 13:34
Show Gist options
  • Save bjoerge/0ebc74364f60e63c5e7751465338dac2 to your computer and use it in GitHub Desktop.
Save bjoerge/0ebc74364f60e63c5e7751465338dac2 to your computer and use it in GitHub Desktop.
treeify
const assert = require('assert')
// takes a flat structure like this
const input = [
{
level: 1,
title: '1'
},
{
level: 1,
title: '2'
},
{
level: 2,
title: '2 1'
},
{
level: 3,
title: '2 1 1'
},
{
level: 2,
title: '2 2'
},
{
level: 1,
title: '3'
},
{
level: 2,
title: '3 1'
},
{
level: 1,
title: '4'
}
]
// And converts it into this
const expected = [
{
level: 1,
title: '1',
children: []
},
{
level: 1,
title: '2',
children: [
{
level: 2,
title: '2 1',
children: [
{
level: 3,
title: '2 1 1',
children: []
}
]
},
{
level: 2,
title: '2 2',
children: []
}
]
},
{
level: 1,
title: '3',
children: [
{
level: 2,
title: '3 1',
children: []
}
]
},
{
level: 1,
title: '4',
children: []
}
]
function treeify(list) {
if (list.length === 0) {
return []
}
const [head, ...tail] = list
const nextIndex = tail.findIndex(item => item.level <= head.level)
return [
setChildren(head, treeify(tail.slice(0, nextIndex))),
...treeify(tail.slice(nextIndex))
]
}
function setChildren(item, children) {
return {
...item,
children
}
}
const actual = treeify(input)
assert.deepEqual(actual, expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment