3
\$\begingroup\$

I'm quite new to js. I even don't know how to call this problem: apply an action on each element of a callback input, but the elements are actually an output..

I crash a lot on this situation: I have a nested callback where first I load a json array and then I perform an action on each element of this array.

$.getJSON(DATA_URL+'/groups', function( groups ) {
    groups.forEach( function(g){
        appendDropdownItem(g);
    } );
});

I want to do it in one line. Not because I think one line is cool but because I think that this nested callback only gets the code dirty and affect readability.

In a pythonic approach I imagine somethings like a comprehension:

[appendDropDownItem(g) for g in loadAjax(DATA_URL+'/groups')]

So.. how to make it one liner/more readable?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

First you can realize that function(x){return f(x)} == f, so you can reduce one line there:

$.getJSON(DATA_URL +'/groups', function(groups){
  groups.forEach(appendDropdownItem)
})

It is harder to go further with these builtin functions. But if you have a curried forEach, with the arguments in the right order, such as the one in Rambda, or in Essentialjs (shameless plug), then you can reduce it even more:

$.getJSON(DATA_URL +'/groups', forEach(appendDropdownItem))

There you got a one readable one-liner.

You can implement your own curried forEach in any case:

var forEach = function(f) {
  return function(xs) {
    return xs.forEach(f)
  }
}

But these libraries include many other helpers that provide a more functional workflow that leads to these one-liners often by means of currying and composition.

\$\endgroup\$
4
  • \$\begingroup\$ nice! what about underscore? \$\endgroup\$
    – nkint
    Commented Sep 17, 2014 at 9:49
  • \$\begingroup\$ underscore doesn't curry functions, and it has the arguments in the wrong order. \$\endgroup\$
    – elclanrs
    Commented Sep 17, 2014 at 10:42
  • \$\begingroup\$ ok so in the end, which functional framework do you advice? \$\endgroup\$
    – nkint
    Commented Sep 18, 2014 at 20:52
  • \$\begingroup\$ Well, I would recommend my own, linked above, but Rambda is more popular, but it is also bigger. If you're using Underscore you can always use partial application, like _.partial(_.each, _, appendDropdownItem), but it looks quite ugly, and you'd have to do this with every function, since the arguments are backwards. \$\endgroup\$
    – elclanrs
    Commented Sep 18, 2014 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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