4
\$\begingroup\$

I have such input:

[ { name: 'timezone', value: 'EST' }, { name: 'interval', value: 'day' }, { name: 'metrics[]', value: 1}, { name: 'metrics[]', value: 2} ] 

As you may already notice - these are parameters from POST request.

What I need to do is to get such output:

[ { name: 'timezone', value: 'EST' }, { name: 'interval', value: 'day' }, { name: 'metrics[]', value: [ 1, 2 ] }, { name: 'metrics[]', value: [ 1, 2 ] } ] 

My code does everything it needs to do, but I'm not sure if it is written in the optimal way, am I overlooking some bugs, etc.

arrayify = (params) -> arrayifiedParams = {} for param in params paramName = param.name arrayifiedParams[paramName] = arrayifiedParams[paramName] || [] arrayifiedParams[paramName].push param.value params.map (param) -> paramName = param.name if arrayifiedParams[paramName].length > 1 param.value = arrayifiedParams[paramName] param 

Here is the corresponding JSFiddle.

\$\endgroup\$
3
  • \$\begingroup\$ For your information, next time you wonder if your question title is good or any concern leave a comment, this will reduce "noise" in your question. You did a good enough job on your question title. Welcome to Code Review! I hope you'll have good review! \$\endgroup\$ Commented Jul 8, 2015 at 17:49
  • 1
    \$\begingroup\$ Do you need to have duplicate objects? \$\endgroup\$ Commented Jul 8, 2015 at 19:17
  • \$\begingroup\$ @elclanrs nope, I don't. Duplicates should be removed later in the code. \$\endgroup\$ Commented Jul 8, 2015 at 19:21

1 Answer 1

3
\$\begingroup\$

Your code looks ok overall. There are perhaps a few CoffeeScript features you can make use of, but nothing major.

However, I don't like that the input array is modified in-place (i.e. the function has side-effects). Other code may hold references to the param objects already, so altering them is potentially dangerous.

I'd rather have the function return a new, separate array with the results, leaving the input array untouched.

Here's a version that does that, and also removes duplicate params (I called it coalesce because it sounds fancier):

coalesce = (params) -> coalesced = {} for param in params {name, value} = param coalesced[name] or= [] coalesced[name].push value for own name, value of coalesced value = value[0] if value.length is 1 {name, value} 
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.