Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ParthBarot-BoTreeConsulting/e55f992af9b6e957250c23c9004448c8 to your computer and use it in GitHub Desktop.
Save ParthBarot-BoTreeConsulting/e55f992af9b6e957250c23c9004448c8 to your computer and use it in GitHub Desktop.
JS Refactoring - second version
// intermediate code
var MyApp = {};
MyApp.Base = {
data: {
rules: {
FirstSet:{
"0-12": {
"0-12000":{
"0-90" :{
fixedVal: 0.4
},
"91-*" :{
fixedVal: 0.7
}
},
"12001-*":{
"0-78" :{
fixedVal: 0.4
},
"78.01-90" :{
fixedVal: 0.7
},
"91-*" :{
fixedVal: 0.9
}
}
},
"13-*": {
"0-12000":{
"0-95" :{
fixedVal: 0.8
},
"96-*" :{
fixedVal: 0.7
}
},
"12001-*":{
"0-95" :{
fixedVal: 1.0
},
"96-*" :{
fixedVal: 1.1
}
}
}
}
}
},
_isDataRangeMatches: function(dataVal,dataRange){
if(dataRange[1] == '*'){
return (dataVal >= parseInt(dataRange[0]));
} else {
return (dataVal >= parseInt(dataRange[0]) && dataVal <= parseInt(dataRange[1]));
}
},
getFixedVal: function(myDataVal, amount, calculatedVal){
var jsonData1 = MyApp.Base.data.rules.FirstSet;
// Loop on the first level keys - "0-12" and "13-*"
for (var key in jsonData1){
if(jsonData1.hasOwnProperty(key)){ //check if the json object has this key
var keyRange1 = key.split('-');
if(this._isDataRangeMatches(myDataVal,keyRange1)){//Call our reusable function if the value is included
var jsonData2 = jsonData1[key]; //Then, get the inner JSON object, say value of this key - "0-12"
//Loop on the second level keys now - "0-12000" and "12001-*"
for (var key1 in jsonData2){
if(jsonData2.hasOwnProperty(key1)){
var keyRange2 = key1.split('-');
if(this._isDataRangeMatches(amount,keyRange2)){//Call our reusable function if the value is included
var jsonData3 = jsonData2[key1];//Then, get the inner JSON object, say value of this key - "0-12000"
//Loop on the third level keys now - "0-90" and "91-*"
for (var key2 in jsonData3){
if(jsonData3.hasOwnProperty(key2)){
var keyRange3 = key2.split('-');
if(this._isDataRangeMatches(calculatedVal,keyRange3)){
//The final check, if it has the fixedVal key then return it.
if(jsonData3[key2].hasOwnProperty('fixedVal')){
return jsonData3[key2].fixedVal;
}
}
}
}
}
}
}
}
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment