Skip to content

Add Ember.reduceComputed, Ember.arrayComputed. - #2711

Merged
tomdale merged 3 commits into
emberjs:masterfrom
hjdivad:array-mixins
Aug 28, 2013
Merged

tomdale merged 3 commits into
emberjs:masterfrom
hjdivad:array-mixins

Conversation

@hjdivad

@hjdivad hjdivad commented May 21, 2013

Copy link
Copy Markdown
Member

Reduce computed properties and computed properties that reduce an enumerable.
Array computed properties are reduce computed properties whose value happens
to be an array.

Reduce computed properties use one-at-a-time semantics to make computations
from arrays pleasant to write without making it easy to introduce O(n²)
runtime for something that only requires O(n).

They can be chained together and retain their O(n) semantics.

A simple example:

 var obj = Ember.Object.createWithMixins({
   items: Ember.A([{
     fname: "Jaime", lname: "Lannister", age: 34
   }, {
     fname: "Cersei", lname: "Lannister", age: 34
   }, {
     fname: "Robb", lname: "Stark", age: 16
   }, {
     fname: "Bran", lname: "Stark", age: 8
   }]),

    lannisters: Ember.computed.filterProperty('items', 'lname',
'Lannister'),
   lannisterSorting: Ember.A(['fname']),
   sortedLannisters: Ember.computed.sort('lannisters', 'lannisterSorting'),

    starks: Ember.computed.filterProperty('items', 'lname', 'Stark'),
   starkAges: Ember.computed.mapProperty('starks', 'age'),
   oldestStarkAge: Ember.computed.max('starkAges')
 });

  var items = obj.get('items');
 // each computed property will have to process only Tyrion to update, rather
 // than having to look through all of `items` again.
 items.pushObject(Ember.Object.create({
   fname: "Tyrion", lname: "Lannister", age: 26
 }));

Sugar functions include:

  • Ember.computed.max
  • Ember.computed.min
  • Ember.computed.map
  • Ember.computed.mapProperty
  • Ember.computed.filter
  • Ember.computed.filterProperty
  • Ember.computed.uniq
  • Ember.computed.intersect
  • Ember.computed.setDiff
  • Ember.computed.sort

They are all implemented with an easily used primitive. The implementation
of
Ember.computed.min serves as an example:

 Ember.computed.min = function (dependentKey) {
   return Ember.reduceComputed.call(null, dependentKey, {
     initialValue: Infinity,

      addedItem: function (accumulatedValue, item, changeMeta, instanceMeta)
{
       return Math.min(accumulatedValue, item);
     },

      removedItem: function (accumulatedValue, item, changeMeta,
instanceMeta) {
       if (item > accumulatedValue) {
         return accumulatedValue;
       }
     }
   });
 };

cc @wagenet

@hjdivad

hjdivad commented May 21, 2013

Copy link
Copy Markdown
Member Author

I believe this makes #1288 unnecessary. Although it does not implement composable mixins, it does handle many of the motivating use cases, including filter-sort chaining.

@hjdivad

hjdivad commented May 21, 2013

Copy link
Copy Markdown
Member Author

@wagenet note that this breaks compatibility slightly because of the naming collision with Ember.computed.map, but I think the original function had surprising semantics, given the name. We can of course easily rename the array computed map to avoid this problem.

@tchak

tchak commented May 22, 2013

Copy link
Copy Markdown
Member

so if I need to filter on several properties I have to create a chain like this?

notNewItems: Em.computed.filterProperty('items', 'isNew', false),
notNewAndNotDeletedItems: Em.computed.filterProperty('items', 'isDeleted', false)

Seems verbose and performance wise this is a disaster... I am not saying this is a bad idea in some simple use cases, but I don't think it is a suitable solution for Filterable/Sortable mixins.

@hjdivad

hjdivad commented May 22, 2013

Copy link
Copy Markdown
Member Author

@tchak I think your complaint is specifically about the Ember.computed.filterProperty sugar, and not the underlying reduceComputed primitive, yes?

I'm happy to improve the sugar functions to be more flexible: it's trivial to have filterProperty support more property-value pairs.

You can also filter by an arbitrary function.

filteredItems: Em.computed.filter('items', function(item) {
  var isNew = item.get('isNew'),
        isDeleted = item.get('isDeleted');

  return !isNew && !isDeleted
})

However there is an issue here: the filter will not rerun when either of the properties change. You can get around this for one property by doing:

filteredItems: Em.computed.filter('[email protected]', function(item) {
  var isNew = item.get('isNew'),
        isDeleted = item.get('isDeleted');

  return !isNew && !isDeleted
})

However, it remains to determine a good syntax for specifying multiple dependent item properties. Personally I'm in favour of

filteredItems: Em.computed.filter('items.@each.{isNew, isDeleted}', function(item) {
  var isNew = item.get('isNew'),
        isDeleted = item.get('isDeleted');

  return !isNew && !isDeleted
})

as it

  1. is very similar to existing syntax
  2. is similar to shell syntax
  3. is terse, but readable

An alternative that is trivial to implement (and, to be clear, can be implemented with the primitive already: it's just not implemented in the sugar) is the following:

filteredItems: Em.computed.filter('[email protected]', '[email protected]', function(item) {
  var isNew = item.get('isNew'),
        isDeleted = item.get('isDeleted');

  return !isNew && !isDeleted
})

I'm less keen on it because of the repetition of items.@each. But this already works, and if it's the core team's preference, I can update the sugar functions to use this approach.

@wycats

wycats commented Jul 4, 2013

Copy link
Copy Markdown
Member

@hjdivad One small issue with stuff like .map. If the mapper returns an object, the removal callback won't know how to remove it. Any ideas?

@tomdale

tomdale commented Jul 4, 2013

Copy link
Copy Markdown
Member

👍 :shipit:

@hjdivad

hjdivad commented Jul 8, 2013

Copy link
Copy Markdown
Member Author

@wycats right now the removal callback removes the item by re-mapping and then removing by identity. For 1-1 transformations like map this is obviously unnecessary.

I think it should suffice to add the index to changeMeta so things like .map can take a shortcut and sugars generally can decide whether to operate on the object or the index.

I'll make that change, although let me know if you see any issue with the approach.

`Ember.TrackedArray` is a data structure for lazily computing indexes of items
in arrays after mutations.

Useful in eg `Ember.ReduceComputed`.
Adds a specialized version of `Ember.TrackedArray` for tracking indexes of items
in arrays that are filtered versions of other arrays.
@hjdivad

hjdivad commented Aug 27, 2013

Copy link
Copy Markdown
Member Author

Still working on making the internals of ReduceComputed easier to follow, but assuming tests pass, this should be good to merge if I don't get more internal cleanup & doc done.

Reduce computed properties and computed properties that reduce an enumerable.
Array computed properties are reduce computed properties whose value happens to
be an array.

Reduce computed properties use one-at-a-time semantics to make computations from
arrays pleasant to write without making it easy to introduce O(n²) runtime for
something that only requires O(n).

They can be chained together and retain their O(n) semantics.

A simple example:

```js
  var obj = Ember.Object.createWithMixins({
    items: Ember.A([{
      fname: "Jaime", lname: "Lannister", age: 34
    }, {
      fname: "Cersei", lname: "Lannister", age: 34
    }, {
      fname: "Robb", lname: "Stark", age: 16
    }, {
      fname: "Bran", lname: "Stark", age: 8
    }]),

    lannisters: Ember.computed.filterProperty('items', 'lname',
'Lannister'),
    lannisterSorting: Ember.A(['fname']),
    sortedLannisters: Ember.computed.sort('lannisters', 'lannisterSorting'),

    starks: Ember.computed.filterProperty('items', 'lname', 'Stark'),
    starkAges: Ember.computed.mapProperty('starks', 'age'),
    oldestStarkAge: Ember.computed.max('starkAges')
  });

  var items = obj.get('items');
  // each computed property will have to process only Tyrion to update, rather
  // than having to look through all of `items` again.
  items.pushObject(Ember.Object.create({
    fname: "Tyrion", lname: "Lannister", age: 26
  }));
```

Sugar functions include:
  - Ember.computed.max
  - Ember.computed.min
  - Ember.computed.map
  - Ember.computed.mapProperty
  - Ember.computed.filter
  - Ember.computed.filterProperty
  - Ember.computed.uniq
  - Ember.computed.intersect
  - Ember.computed.setDiff
  - Ember.computed.sort

They are all implemented with an easily used primitive.  The implementation of
`Ember.computed.min` serves as an example:

```js
  Ember.computed.min = function (dependentKey) {
    return Ember.reduceComputed.call(null, dependentKey, {
      initialValue: Infinity,

      addedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
        return Math.min(accumulatedValue, item);
      },

      removedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
        if (item > accumulatedValue) {
          return accumulatedValue;
        }
      }
    });
  };
```
tomdale added a commit that referenced this pull request Aug 28, 2013
Add `Ember.reduceComputed`, `Ember.arrayComputed`.
@tomdale
tomdale merged commit a49a9bb into emberjs:master Aug 28, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants