Created
September 27, 2017 13:34
-
-
Save bjoerge/0ebc74364f60e63c5e7751465338dac2 to your computer and use it in GitHub Desktop.
treeify
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
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