Skip to content

Instantly share code, notes, and snippets.

@AlxGolubev
Created December 13, 2018 09:39
Show Gist options
  • Save AlxGolubev/67b9efeb1668e638a7489c00659225e7 to your computer and use it in GitHub Desktop.
Save AlxGolubev/67b9efeb1668e638a7489c00659225e7 to your computer and use it in GitHub Desktop.

Revisions

  1. AlxGolubev created this gist Dec 13, 2018.
    68 changes: 68 additions & 0 deletions recursive-sorting.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    const R = require('ramda')

    const kind = 'desc'

    let collection = {
    nodes: [
    {
    name: 'Items',
    children: [
    {
    name: 'very-old-2',
    children: [
    { name: 'very-new-old-2.2-last-try-final' },
    { name: 'very-new-old-2.3-last-try-final' }
    ]
    },
    {
    name: 'very-old-1',
    children: [
    { name: 'very-new-old-1.2-last-try-final' },
    { name: 'very-new-old-1.3-last-try-final' }
    ]
    }]
    }
    ]
    }

    const sortNormalization = (propName) =>
    R.compose(
    R.toLower,
    R.prop(propName)
    )

    const sortStrategy = (type) =>
    R.ifElse(
    R.equals('asc'),
    () => R.ascend,
    () => R.descend
    )(type)

    const alphabeticalSortWithProp = (propName, type) =>
    R.compose(
    R.sort,
    sortStrategy(type),
    sortNormalization
    )(propName)


    const sortCollection = (entries) => R.compose(
    alphabeticalSortWithProp('name', kind),
    sortDescedants
    )(entries)

    const sortDescedants = (nodes) => {
    return nodes.map(
    entry => {
    if (entry.children) {
    entry.children = sortCollection(entry.children)
    }

    return entry
    }
    )
    }

    collection = sortCollection(collection.nodes)

    console.dir(collection, { depth: 10, colors: true })