ES6 Assign a variable with an arrow function
You create an anonymous function but do not execute it.
For example:
var getResponseData = () => {
switch (payload.returnType.toLowerCase()) {
case "json" : return JSON.parse(httpRequest.responseText);
case "text" : return httpRequest.responseText;
default : return null;
}
};
callback(null, getResponseData());
I think your hunch is right, but you're on the wrong track, imho. What I think you want to do is create a map of response types to callbacks:
let parsers = new Map([
["json", JSON.parse],
["text", (text) => text],
["_", () => null]
]), t = payload.returnType.toLowerCase();
if (!parsers.has(t)) {
t = "_";
}
callback(null, parsers.get(t)(httpRequest.responseText))
What makes this subjectively "cleaner" is that you separate logic from implementation. You can move the parser definition anywhere without affecting the code. That's why switch statements feel "unfunctional" (or undeclarative).
But of course, this all remains a matter of taste :)
Even shorter with a self-executing function:
const res = (() => {
return 'something'
})()
or even shorter if it's a one-liner:
const res = (() => 'something')()
Or with your code:
var getResponseData = (() => {
switch (payload.returnType.toLowerCase()) {
case "json" : return JSON.parse(httpRequest.responseText);
case "text" : return httpRequest.responseText;
default : return null;
}
})();
You can clearly see the difference in this snippet:
const res1 = () => {
return 'something'
}
const res2 = (() => {
return 'something'
})()
const res3 = (() => 'short something')()
console.log(res1)
console.log(res2)
console.log(res3)