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)
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…