jashkenas / jashkenas/underscore

Underscore could use a _.propertyResult

Open
#2,286 3 comments 0 reactions 0 assignees View on GitHub
contrib enhancement
Dominant language
JavaScript
Stars
27.3k
Forks
5.4k
Avg merge
2d 5h
Merged PRs (30d)
1

Description

The new `_.property` is really neat, and I love using it, but there's one problem: it only returns static values.

For instance, let's say I want to find out if any object in an array contains has an `isNew` property; I can do the following:

```
var objects = [{isNew: true}, {isNew: false}];

_(objects).any(_('isNew').property()); // === true
```

That's a lot better than before `property`, when I had to do:

```
_(objects).any(function(x) { return x.isNew; });
```

But what if instead of random objects I have a bunch of `Backbone.Model` objects. Those don't have an `isNew` property, they have an `isNew` _method_. So:

```
_(objects).any(_('isNew').property());
```

won't work; instead I'm back to the old style:

```
_(objects).any(function(x) { return _(x).result('isNew'); });
```

or (if I combine `partial` and `result`):

```
_(objects).any(function(_(_.result).partial(_, 'isNew'));
```

It would be really great if there was a method that was just like `_.property`, except that if it would return a function, it returns the result of executing that function instead (like `_.result`). In other words, if I could do ...

```
_(objects).any(_('isNew').propertyResult());
```

Since it's a fairly common practice to have `is*` methods on objects, and also common practice to want to use Underscore methods like `any` or `filter` with those methods, I really think this would be a useful addition to the library.

Contributor guide

Open the contributing guide

Research direction

Read the existing _.property and _.result entry points and their surrounding implementation to understand how each handles object values and methods. Add the requested propertyResult behavior and verify that it returns static properties unchanged while executing function-valued properties; update the relevant tests if the project has coverage for these methods.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.