Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
56 views
in Technique[技术] by (71.8m points)

javascript - Recursive calls between two functions

I need to recursive check two objects and keys need to be sorted, so I created two functions.

buildObj - get all uniq keys from object, sort them and call buildObjKey on each key

buildObjKey - if one of values is object call buildObj for these. Other returns is example and real code is more complex.

So question: I define buildObj before buildObjKey and call buildObjKey while its not defined yet. This is bad practice, but if I move definition of buildObj after buildObjKey I will call buildObj before It was defined... This is possible to do recursive calls between two functions without this trouble?

const _ = require('lodash')

const example1 = {
  key3: 'foo',
  key1: {
    key4: {
      key6: 'boo'
    },
  },
}

const example2 = {
  key3: 'too',
  key1: {
    key4: {
      key6: 'hoo'
    },
  },
}

const buildObj = (obj1, obj2) => {
 return  _.uniq([...Object.keys(obj1), ...Object.keys(obj2)])
 .sort()
 .map(key => buildObjKey(key, obj1, obj2))
}

const buildObjKey = (key, obj1, obj2) => {
  const val1 = obj1[key];
  const val2 = obj2[key];
  if(val1 && val2){
    if(_.isObject(val1) && _.isObject(val2)){
      return buildObj(val1, val2)
    }
    if(_.isObject(val1)){
      return buildObj(val1, val1)
    }
    if(_.isObject(val2)){
      return buildObj(val2, val2)
    }
    return val1
  }
  return val1 || val2
}

buildObj(example1, example2)

enter image description here

Execution example [ [ [ 'boo' ] ], 'foo' ]

The real code is doing diff of two object, i don't write it here because of complexity. Here is simple example of structure.

question from:https://stackoverflow.com/questions/65651581/recursive-calls-between-two-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So there are a number of ways you can get around this problem & I'd honestly say that it may depend on what you consider important, i.e. it may depend on your style of coding & what preferences you have.


Hoisting

A simple enough technique to use, feel free to read up more on MDN, but in a nutshell hoisting is where you declare a variable towards the start of the file, then use it at some later point. But with functions specifically all you need to do to make use of this concept is define them as traditional functions. The idea being that when you define a function using the keyword function, the function essentially gets defined before other variables within the scope.

Here's a little example:

test();

function test() {
  console.log("Hello! :)")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...