Raynos / observ-array

An array containing observable values
MIT License
26 stars 4 forks source link

Efficient `computedFilter()` and `computedMap()` #3

Open Raynos opened 10 years ago

Raynos commented 10 years ago

Currently when you call map() and filter() on an array you get a static computed copy.

var doubles = list.map(function (o) {
  return computed([o], function (v) { return v * 2 })
})

This works fine if you never add or remove items from list and doubles will performantly only do updates to the values that actually update in list.

However we want to support a computedFilter and computedMap that listens to all changes on the array including additions and removals.

See knockout-projections for an implementation of computedFilter and computedMap for knockoutJS.

I have a previous buggy / untested implementation of computedFilter here

cc @Matt-Esch would appreciate advice on performance

Raynos commented 10 years ago

For sanity computedFilter() and computedMap() should not return mutable observ-array instances. They should return computed read only arrays.

kristianmandrup commented 9 years ago

I think it is better with a proxy on top, a layer that can be added or removed ;) keep it flexible...

kristianmandrup commented 9 years ago

use freeze on array I guess :)

kristianmandrup commented 9 years ago

I will look at this tmrw, you are most welcome to do a head start if you got a few mins or hours ;) I can see it would make a very nice addition indeed!

Also check out: http://emberjs.com/api/classes/Ember.ArrayProxy.html

and especially http://emberjs.com/api/classes/Ember.MutableArray.html

addArrayObserver (target, opts) Ember.Array Inherited from Ember.Array packages/ember-runtime/lib/mixins/array.js:330 Adds an array observer to the receiving array. The array observer object normally must implement two methods:

arrayWillChange(observedObj, start, removeCount, addCount) - This method will be called just before the array is modified.

arrayDidChange(observedObj, start, removeCount, addCount) - This method will be called just after the array is modified.

This way it keeps track of the index where change was made and how many elements were added removed starting at that index. Pretty clever IMO ;)