I would like to know is there any alternative method for a function in my scenario in javascript
Below function works fine, but is there any alternative method to do, since there are more obj
//will get single object as response as anyof these
obj ={"id":"trans", "cn": "SG", "ccy": "SGD"};
obj ={"id": "remit", "cn": "TH", "ccy": "THB"};
obj ={"id": "fund", "cn": "IN", "ccy": "INR"};
function getTrans(){
var value = 1000;
var rate = 0.5;
return value * rate;
}
function getFund(){
var value = 2000;
var rate = 0.2;
return value * rate;
}
var result = getData(obj);
function getData(obj){
if(obj.id==="trans"){
return getTrans(obj);
}
else if(obj.id==="fund"){
return getFund(obj);
}
else{
return obj;
}
}
2 Answers 2
You would usually write a map letting you access your function, for example
//will get object as response
var obj ={"id":"trans", "cn": "SG", "ccy": "SGD"};
var obj ={"id": "remit", "cn": "TH", "ccy": "THB"};
var obj ={"id": "fund", "cn": "IN", "ccy": "INR"};
const extractors = {
trans(obj) {
var value = 1000;
var rate = 0.5;
return value * rate;// this should probably use obj
},
fund(obj) {
var value = 2000;
var rate = 0.2;
return value * rate;
}
}
function getData(obj){
let extractor = extractors[obj.id];
return extractor ? extractor(obj) : obj;
}
var result = getData(obj);
If you have other similar functions to associate to your ids, you could use objects instead of functions:
const handlers = {
trans: {
getData: obj => ...,
foo: obj => ...
},
...
and then access the functions with
function getData(obj){
let handler = handlers[obj.id];
return handler ? handler.getData(obj) : obj;
}
This kind of pattern is very extensible and is suited to injections, meaning you can have a global getData code not aware of the various types, but other parts of your applications registering new handlers.
Comments
class ObjX{
constructor(id,cn,ccy){
this.id=id;
this.cn=cn;
this.ccy=ccy;
}
trans=function(){
var value = 1000;
var rate = 0.5;
return value * rate;
}
fund=function(){
var value = 2000;
var rate = 0.2;
return value * rate;
}
getData(){
if(this[this.id]){
return this[this.id]();
}else{
return this;
}
}
}
obj =new ObjX("trans","SG","SGD");
obj2 =new ObjX("remit","TH","THB");
obj3 =new ObjX("fund","SG","INR");
console.log(obj.trans());
console.log(obj.getData());
console.log(obj2.getData());
console.log(obj3.getData());
Try this magic!
var objin the code?objthere will be single obj only, will get trans or fund or insta