Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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];
share|improve this question

migrated from programmers.stackexchange.com Aug 24 at 6:26

This question came from our site for professional programmers interested in conceptual questions about software development.

    
Why would you want to? – Robert Harvey Aug 24 at 3:52
1  
because it's midnight, mainly. just exploring. – Mega Man Aug 24 at 3:54
1  
In my understanding, your first approach was better. You are adding an extra and unnecessary iteration because of .map. Also, self is a conventional name for context variable. This will reduce the readability instead. – Rajesh Aug 24 at 7:46
    
@Rajesh I agree with the poor name, and agree that the second is less readable. – Mega Man Aug 24 at 12:45
up vote 4 down vote accepted

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.

share|improve this answer

You could use Object.assign too.

It does mutate the acc but it's localized to the reduce call.

endpoints[endpoint].reduce((acc, e) =>
  Object.assign(acc, { [e]: `endpoint/${e}` }), {})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.