Please go through below code and improve the quality by reducing the IF conditions:
I have 2 jsons, first one is the source and second one is the updated json. I have to compare both values and set true/false flags. Based on the flags i need to proceed further.
I am checking below conditions:
- NULL changed to DECLINED
- NULL changed to a VALUE
- VALUE changed to DECLINED
- VALUE1 changed to VALUE2
O/P - canProceed = (nullDec) ? (nullDec && (nullVal || valDec || valVal)) :(nullVal || valDec || valVal);
Plnkr - https://plnkr.co/edit/gKJXibTFQhInBOhz?open=lib%2Fscript.js
import angular from 'angular';
angular.module('plunker', []).controller('MainCtrl', function($scope) {
$scope.name = 'Plunker';
var json1={id:"01", name:"Jon", city:null, state:"NY", phone:null, zip:"06033"};
var json2={id:"02", name:"Kris", city:"DECLINED", state:"DECLINED", phone:"860-000-0000", zip:"06033"};
var json3={id:"02", name:"Sam", city:"EDISON", state:"DECLINED", phone:"860-000-0000", zip:"06033"};
compareJsons(json1, json2);
function compareJsons(model1, model2){
console.log(model1);
console.log(model2);
var decline = "DECLINED";
var canProceed = false;
var nullVal = false;
var nullDec = false;
var valDec = false;
var valVal = false;
angular.forEach(model1, function(m1Val, m1Key){
if(!m1Val){
console.log("Found NULL - "+ m1Key +" - " + m1Val);
angular.forEach(model2, function(m2Val, m2Key){
if((m2Key === m1Key) && (m2Val !== m1Val)){
console.log(m1Key +" - " + m1Val + " CHANGED TO " + m2Key +" - " + m2Val);
if((m2Val === decline) && !(m1Val)){
nullDec = true;
}
if(((m2Val) && (m2Val !== decline)) && !(m1Val)){
nullVal = true;
}
}
})
} else {
angular.forEach(model2, function(m2Val, m2Key){
if(m2Key === m1Key && m2Val !== m1Val){
if(m2Val === decline){
console.log(m1Key +" - " + m1Val + " CHANGED TO " + m2Key +" - " + m2Val);
if(((m1Val) && (m1Val !== decline)) && (m2Val)){
valDec = true;
}
}else{
console.log(m1Key +" - " + m1Val + " CHANGED TO " + m2Key +" - " + m2Val);
if((m1Val) && (m2Val)){
valVal = true;
}
}
}
});
}
});
console.log("NULL to DECLINE - " + nullDec);
console.log("NULL to VALUE - " + nullVal);
console.log("VALUE to DECLINE - " + valDec);
console.log("VALUE1 to VALUE2 - " + valVal);
canProceed = (nullDec) ? (nullDec && (nullVal || valDec || valVal)):(nullVal || valDec || valVal);
console.log("Can Proceed - " + canProceed);
}
});