Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Last active August 6, 2020 20:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleshevlin/ed4025f807235a4559a67d47981c0890 to your computer and use it in GitHub Desktop.
Save kyleshevlin/ed4025f807235a4559a67d47981c0890 to your computer and use it in GitHub Desktop.
function flattenFolderTree(folders) {
return folders.reduce((acc, folder) => {
const {children, ...rest} = folder;
if (!children || !children.length) {
return [...acc, rest];
}
return [...acc, rest, ...flattenFolderTree(children)];
}, []);
}
@joelnet
Copy link

joelnet commented Aug 5, 2020

Something I have been considering when using reducers is to expose the reducer itself as the tool.

function flattenFolderTreeReducer(acc, folder) {
  const {children, ...rest} = folder;

  if (!children || !children.length) {
    return [...acc, rest];
  }

  return [...acc, rest, ...children.reduce(flattenFolderTreeReducer, [])];
}

// use it with something like this:
folders.reduce(flattenFolderTreeReducer, [])

The only benefit to this is it would let someone dot chain off the Array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment