2
\$\begingroup\$

I stopped using Lodash to become better at JavaScript. These are recursive utility functions to deal with nested arrays:

const _ = {}

// find object in nested arrays
_.findDeep = (arr, obj) => {
  return arr.map(item => {
    const key = _.keys(obj)[0]
    if (item[key] === obj[key]) return arr
    if (item.children) return _.findDeep(item.children, obj)
    return undefined
  }).reduce((prev, curr) => {
    return prev || curr
  })
}

// insert new object above an object in nested array
_.insertUpDeep = (arr, obj, newObj) => {
  let found = _.findDeep(arr, obj)
  if (found) found.splice(found.indexOf(obj), 0, newObj)
  return arr
}

// TODO rename this into something less suggestive
_.insertDownDeep = (arr, obj, newObj) => {
  let found = _.findDeep(arr, obj)
  if (found) found.splice(found.indexOf(obj) + 1, 0, newObj)
  return arr
}

// same as the two above, but create a container for the
// two objects so they can have their own flow. e.g.
// flex-direction: row/column
_.insertLeftDeep = (arr, bj, newObj, contObj) => {
  let found = _.findDeep(arr, obj)
  if (found) {
    contObj.children.push(obj)
    contObj.children.push(newObj)
    found.splice(found.indexOf(obj), 0, contObj)
    found.splice(found.indexOf(obj), 1) // to avoid duplicating obj
  }
  return arr
}

export default _

Example input:

const colors = {
   name: 'orange'
   children: [{
     name: 'white'
   }, {
     name: 'green',
     children: [{
       name: 'yellow',
       children: [{
         name: 'red'
       }, {
         name: 'white'
       }]
     }, {
       name: 'green',
       children: [{
         name: 'purple',
         color: 'purple',
         path: 'writer'
       }]
     }]
   }, {
     name: 'gray'
   }]
 }

 const color = {
   name: 'brown'
 }

 const newColor = {
   name: 'white'
 }

 const container = {
   name: 'container'
   children: [
     color
   ]
 }

 insertUpDeep(colors, color, newColor)
 insertLeftDeep(colors, color, newColor, container)

I would like to know how to 1) make it simpler/easier to read 2) make it flexible as modularized as Lodash functions.

(I'm specially concerned about the number of parameters that insertLeftDeep has. It's easy to forget which arguments it's supposed to have.)

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.