Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_.constant Function #402

Closed
OttoAllmendinger opened this issue Dec 12, 2011 · 5 comments
Closed

_.constant Function #402

OttoAllmendinger opened this issue Dec 12, 2011 · 5 comments

Comments

@OttoAllmendinger
Copy link

It would be nice to have a function like

_.constant = function(x) { return function() { return x; }}

I have often needed something like _.constant(true) or _.constant(false) when filtering collections with a configurable iterator.

@jashkenas
Copy link
Owner

This is a very interesting function -- but I'm afraid that I fail entirely to see the use-case where this would be helpful. Instead of filtering a collection by true, why not just duplicate the collection ... instead of filtering it by false, why not just use an empty array?

Provide some real-world code that makes use of this idiom, and we'll reopen the ticket.

@OttoAllmendinger
Copy link
Author

There is an analogue in Clojure core: constantly

I admit the usage is a little subtle, but I'll try to demonstrate.

Consider

_.isUndefined(filterFunc) ? collection : _.filter(collection, filterFunc);

_.select(collection, filterFunction || function() { return true; })

_.select(collection, filterFunction || _.constant(true))

Graphics

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

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

Testing/Stubbing

textDisplay.source = { getText: _.constant("text") }

@jashkenas
Copy link
Owner

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

Still, I think it would be clearer for most readers, and not much longer, to simply write the function:

circle.position = function(){ return [10, 10]; };

image.fill(function(){ return black; });

@OttoAllmendinger
Copy link
Author

That is correct, though the same can be said for _.identity.

I also think the word constant is more expressive than having to parse the code and see if the return value is indeed constant.

@sophiebits
Copy link

This would also be useful if you need a function that returns a particular this:

var self = this;
return $.ajax(...).then(function() { return self });

// vs

return $.ajax(...).then(_.constant(this));

I agree that there isn't a huge difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants