Mega Man Mega Man - 3 months ago 11
Javascript Question

Functional JavaScript, remove assignment

How can I avoid the

self
variable here?

function urlBuilder(endpoint){
var status = ["user_timeline", "home_timeline", "retweets_of_me", "show", "retweets",
"update", "update_with_media", "retweet", "unretweet", "retweeters", "lookup"
],
friendships = ["incoming", "outgoing", "create", "destroy", "update", "show"];
let endpoints = {
status: status,
friendships: friendships
}

var self = { };

endpoints[endpoint].forEach(e => {
self[e] = endpoint + "/" + e;
});

return self;

}


somewhat better, still an assignment statement.

return [{}].map(el => {
endpoints[endpoint].forEach(e => {
el[e] = endpoint + "/" + e;
});
return el;
})[0];

Answer

You cannot really. To create an object with a dynamic number of properties (and without using JSON.parse) you always need to mutate it by assignment or something similar.

Your best bet might be

return endpoints[endpoint].reduce((self, e) => {
    self[e] = endpoint + "/" + e;
    return self;
}, {});

which is quite functional.