Skip to content Skip to sidebar Skip to footer

Can I Make This Function Defenition Even Shorter?

I am trying move more towards functional programming in my javascript applications. I currently use the library ramda as a base lib for this. My desire: Create a function findWit

Solution 1:

Ramda does have a function that will help with this, one called useWith. If you can think of a better name, I'd love it. I've asked that before.

You can use is like this:

var findById = R.useWith(R.find, hasId, R.identity);

var find5 = findById(5);
find5([{id:3}, {id:5}]); //=> {id:5} 
findById(5, [{id:3}, {id:5}]); //=> {id:5} 

You don't have to supply R.identity above. This would also work, although I prefer to be explicit:

var findById = R.useWith(R.find, hasId);

useWith "accepts a function fn and any number of transformer functions and returns a new function. When the new function is invoked, it calls the function fn with parameters consisting of the result of calling each supplied handler on successive arguments to the new function"

Solution 2:

You're looking for the compose function:

compose :: (a -> b) -> (b -> c) -> (a -> c)
hasId :: p -> (i -> Boolean)
find :: (i -> Boolean) -> ([i] -> i | undefined)
compose :: (p -> (i -> Boolean))
           -> ((i -> Boolean) -> ([i] -> i | undefined))
           -> (p -> ([i] -> i | undefined))
compose find hasId :: p -> ([i] -> i | undefined)

So you'd do

var findWithId = R.compose(R.find, hasId)

Oh, and notice that you don't need a function expression for hasId either:

var hasId = R.propEq('_id');

Post a Comment for "Can I Make This Function Defenition Even Shorter?"