Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one need to use lodash/fp/constant?

Why would one need to use .constant(value) from lodash/fp/constant? I saw some other guys use _.constant(true) or _.constant(1) but don't really know what is the benefit of it.

From what I know .constant(value) return a function that returns the given value. I know it has something to do with functional programming, but why don't just use const VALUE = 1; instead?

like image 855
Huy Vo Avatar asked Oct 19 '25 06:10

Huy Vo


2 Answers

One usecase would be to fill an array on creation:

  Array.from({length: 5}, _.constant(1))

but without it would be actually shorter:

  Array.from({length: 5}, () => 1);
like image 55
Jonas Wilms Avatar answered Oct 21 '25 21:10

Jonas Wilms


From https://github.com/jashkenas/underscore/issues/402#issuecomment-3112193:

// api: object.position = function(time) { return coords }
circle.position = _.constant( [10, 10] )

// api: image.fill( function(x, y) { return color })
image.fill( _.constant( black ) );

So, mainly for passing constants to APIs that expect functions. Nice.

like image 34
Brian Kung Avatar answered Oct 21 '25 19:10

Brian Kung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!