// ========================================================================== // Project: SproutCore Costello - Property Observing Library // Copyright: ©2006-2009 Sprout Systems, Inc. and contributors. // Portions ©2008-2009 Apple Inc. All rights reserved. // License: Licened under MIT license (see license.js) // ========================================================================== require('core') ; require('system/enumerator'); /*globals Prototype */ /** @namespace This mixin defines the common interface implemented by enumerable objects in SproutCore. Most of these methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific features that cannot be emulated in older versions of JavaScript). This mixin is applied automatically to the Array class on page load, so you can use any of these methods on simple arrays. If Array already implements one of these methods, the mixin will not override them. h3. Writing Your Own Enumerable To make your own custom class enumerable, you need two items: 1. You must have a length property. This property should change whenever the number of items in your enumerable object changes. If you using this with an SC.Object subclass, you should be sure to change the length property using set(). 2. If you must implement nextObject(). See documentation. Once you have these two methods implement, apply the SC.Enumerable mixin to your class and you will be able to enumerate the contents of your object like any other collection. h3. Using SproutCore Enumeration with Other Libraries Many other libraries provide some kind of iterator or enumeration like facility. This is often where the most common API conflicts occur. SproutCore's API is designed to be as friendly as possible with other libraries by implementing only methods that mostly correspond to the JavaScript 1.8 API. @static @since SproutCore 1.0 */ SC.Enumerable = { /** Walk like a duck. */ isEnumerable: YES, /** Implement this method to make your class enumerable. This method will be call repeatedly during enumeration. The index value will always begin with 0 and increment monotonically. You don't have to rely on the index value to determine what object to return, but you should always check the value and start from the beginning when you see the requested index is 0. The previousObject is the object that was returned from the last call to nextObject for the current iteration. This is a useful way to manage iteration if you are tracing a linked list, for example. Finally the context paramter will always contain a hash you can use as a "scratchpad" to maintain any other state you need in order to iterate properly. The context object is reused and is not reset between iterations so make sure you setup the context with a fresh state whenever the index parameter is 0. Generally iterators will continue to call nextObject until the index reaches the your current length-1. If you run out of data before this time for some reason, you should simply return undefined. The default impementation of this method simply looks up the index. This works great on any Array-like objects. @param index {Number} the current index of the iteration @param previousObject {Object} the value returned by the last call to nextObject. @param context {Object} a context object you can use to maintain state. @returns {Object} the next object in the iteration or undefined */ nextObject: function(index, previousObject, context) { return this.objectAt ? this.objectAt(index) : this[index] ; }, /** Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. If you override this method, you should implement it so that it will always return the same value each time it is called. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return undefined. @returns {Object} the object or undefined */ firstObject: function() { if (this.get('length')===0) return undefined ; if (this.objectAt) return this.objectAt(0); // support arrays out of box // handle generic enumerables var context = SC.Enumerator._popContext(), ret; ret = this.nextObject(0, null, context); context = SC.Enumerator._pushContext(context); return ret ; }.property(), /** Returns a new enumerator for this object. See SC.Enumerator for documentation on how to use this object. Enumeration is an alternative to using one of the other iterators described here. @returns {SC.Enumerator} an enumerator for the receiver */ enumerator: function() { return SC.Enumerator.create(this); }, /** Iterates through the enumerable, calling the passed function on each item. This method corresponds to the forEach() method defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): {{{ function(item, index, enumerable) ; }}} - *item* is the current item in the iteration. - *index* is the current index in the iteration - *enumerable* is the enumerable object itself. Note that in addition to a callback, you can also pass an optional target object that will be set as "this" on the context. This is a good way to give your iterator function access to the current object. @params callback {Function} the callback to execute @params target {Object} the target object to use @returns {Object} this */ forEach: function(callback, target) { if (typeof callback !== "function") throw new TypeError() ; var len = this.get ? this.get('length') : this.length ; if (target === undefined) target = null; var last = null ; var context = SC.Enumerator._popContext(); for(var idx=0;idx 1) { for(idx=1;idx 2) { for(idx=2;idx previousValue) ? item : previousValue ; }, /** Reducer for @maxObject reduced property. */ reduceMaxObject: function(previousItem, item, index, e, reducerProperty) { // get the value for both the previous and current item. If no // reducerProperty was supplied, use the items themselves. var previousValue = previousItem, itemValue = item ; if (reducerProperty) { if (item) { itemValue = item.get ? item.get(reducerProperty) : item[reducerProperty] ; } if (previousItem) { previousValue = previousItem.get ? previousItem.get(reducerProperty) : previousItem[reducerProperty] ; } } if (previousValue === null) return item ; return (itemValue > previousValue) ? item : previousItem ; }, /** Reducer for @min reduced property. */ reduceMin: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } if (previousValue === null) return item ; return (item < previousValue) ? item : previousValue ; }, /** Reducer for @maxObject reduced property. */ reduceMinObject: function(previousItem, item, index, e, reducerProperty) { // get the value for both the previous and current item. If no // reducerProperty was supplied, use the items themselves. var previousValue = previousItem, itemValue = item ; if (reducerProperty) { if (item) { itemValue = item.get ? item.get(reducerProperty) : item[reducerProperty] ; } if (previousItem) { previousValue = previousItem.get ? previousItem.get(reducerProperty) : previousItem[reducerProperty] ; } } if (previousValue === null) return item ; return (itemValue < previousValue) ? item : previousItem ; }, /** Reducer for @average reduced property. */ reduceAverage: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } var ret = (previousValue || 0) + item ; var len = e.get ? e.get('length') : e.length; if (index >= len-1) ret = ret / len; //avg after last item. return ret ; }, /** Reducer for @sum reduced property. */ reduceSum: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } return (previousValue === null) ? item : previousValue + item ; } } ; // Apply reducers... SC.mixin(SC.Enumerable, SC.Reducers) ; SC.mixin(Array.prototype, SC.Reducers) ; Array.prototype.isEnumerable = YES ; // ...................................................... // ARRAY SUPPORT // // Implement the same enhancements on Array. We use specialized methods // because working with arrays are so common. (function() { // These methods will be applied even if they already exist b/c we do it // better. var alwaysMixin = { // this is supported so you can get an enumerator. The rest of the // methods do not use this just to squeeze every last ounce of perf as // possible. nextObject: SC.Enumerable.nextObject, enumerator: SC.Enumerable.enumerator, firstObject: SC.Enumerable.firstObject, sortProperty: SC.Enumerable.sortProperty, // see above... mapProperty: function(key) { var len = this.length ; var ret = []; for(var idx=0;idx 1) { for(idx=1;idx 2) { for(idx=2;idx