Last active
May 9, 2017 01:44
-
-
Save granmoe/8400bee939af4850064edc27a1e0d57e to your computer and use it in GitHub Desktop.
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
// 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