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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With