I have a javascript function which does its job.
However, I have duplicate code and I'm not so familiar with JS at all really.
So I was wondering if you could give me a hand and suggest a design pattern to avoid the duplicate code.
(function () {
var header = 'bla';
var url = 'bla';
var incomingStuff = fetchingSomeData...;
var A_Request = {
"JSONExample": {
"1": { "1": "1" },
"2": { "2": "2" }
}
};
var B_Request = {
"JSONExample2": {
"1": { "1": "1" }
}
};
var C_Request = {
"JSONExample3": {
"3": [
{
"4": {
"5": "bla"
}
}
]
}
};
function create_A() {
return http.put({
url: url + "somecustomstring_A/",
headers: header,
data: A_Request
}).extractOrElse(
function (result) {
print("OK");
return result;
},
function (e) {
print("NOT OK");
return e;
});
}
function create_B() {
return http.put({
url: url + "somecustomstring_B/",
headers: header,
data: B_Request
}).extractOrElse(
function (result) {
print("OK");
return result;
},
function (e) {
print("NOT OK");
return e;
});
}
function create_C() {
return http.put({
url: url + "somecustomstring_C/",
headers: header,
data: C_Request
}).extractOrElse(
function (result) {
print("OK");
return result;
},
function (e) {
print("NOT OK");
return e;
});
}
function createResult() {
if (incomingStuff.whatToDo === 'A') {
return create_A();
} else if (incomingStuff.whatToDo === 'B') {
return create_B();
} else if (incomingStuff.whatToDo === 'C') {
return create_C();
}
}
return createResult();
})();
The problem mainly is the identical logic inside the three create functions. I think it would be much more readable if there was some pattern, as the amount of create functions will extend in the future also.
Any help is appreciated, thanks in advance.
Aucun commentaire:
Enregistrer un commentaire