Skip to content

Instantly share code, notes, and snippets.

@granmoe
Last active May 9, 2017 01:44
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 granmoe/8400bee939af4850064edc27a1e0d57e to your computer and use it in GitHub Desktop.
Save granmoe/8400bee939af4850064edc27a1e0d57e to your computer and use it in GitHub Desktop.
// must run in a context where Immutable is available, like in the console here: https://facebook.github.io/immutable-js/docs/#/
const flattenList = items => {
return items.reduce((result, item) => {
result = result.push(item)
return item.has('children') ? result.concat(flattenList(item.get('children'))) : result
}, Immutable.List())
}
const nestedList = [
{
value: '1',
children: [
{ value: '1.1' },
{ value: '1.2' }
]
}, {
value: '2',
children: [
{ value: '2.1' }
]
}, {
value: '3',
children: [
{ value: '3.1',
children: [
{
value: '3.1.1'
}, {
value: '3.1.2'
}
]
}
]
}
]
const nestedImmutableList = Immutable.fromJS(nestedList)
const flattenedImmutableList = flattenList(nestedImmutableList)
const expectedResult = ["1", "1.1", "1.2", "2", "2.1", "3", "3.1", "3.1.1", "3.1.2"]
flattenedImmutableList.map( list => list.get('value') ).equals(Immutable.fromJS(expectedResult)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment