1 // ========================================================================== 2 // Project: SproutCore Costello - Property Observing Library 3 // Copyright: ©2006-2011 Strobe Inc. and contributors. 4 // Portions ©2008-2011 Apple Inc. All rights reserved. 5 // License: Licensed under MIT license (see license.js) 6 // ========================================================================== 7 8 sc_require('mixins/array'); 9 10 SC.supplement(Array.prototype, SC.CoreArray); 11 12 // Because Arrays are dealt with so much, we add specialized functions. 13 14 SC.mixin(Array.prototype, 15 /** @lends Array.prototype */ { 16 17 // primitive for array support. 18 replace: function (idx, amt, objects) { 19 if (this.isFrozen) { throw new Error(SC.FROZEN_ERROR); } 20 21 var args; 22 var len = objects ? (objects.get ? objects.get('length') : objects.length) : 0; 23 24 // Notify that array content is about to mutate. 25 this.arrayContentWillChange(idx, amt, len); 26 27 if (len === 0) { 28 this.splice(idx, amt); 29 } else { 30 args = [idx, amt].concat(objects); 31 this.splice.apply(this, args); 32 } 33 34 this.arrayContentDidChange(idx, amt, len); 35 36 return this; 37 }, 38 39 // If you ask for an unknown property, then try to collect the value 40 // from member items. 41 unknownProperty: function (key, value) { 42 var ret = this.reducedProperty(key, value); 43 if ((value !== undefined) && ret === undefined) { 44 ret = this[key] = value; 45 } 46 return ret; 47 } 48 49 }); 50 51 if (Array.prototype.indexOf === SC.CoreArray.indexOf) { 52 /** 53 Returns the index for a particular object in the index. 54 55 @param {Object} object the item to search for 56 @param {Number} startAt optional starting location to search, default 0 57 @returns {Number} index of -1 if not found 58 */ 59 Array.prototype.indexOf = function (object, startAt) { 60 var idx, len = this.length; 61 62 if (startAt === undefined) startAt = 0; 63 else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); 64 if (startAt < 0) startAt += len; 65 66 for (idx = startAt; idx < len; idx++) { 67 if (this[idx] === object) return idx; 68 } 69 return -1; 70 }; 71 } 72 73 if (Array.prototype.lastIndexOf === SC.CoreArray.lastIndexOf) { 74 /** 75 Returns the last index for a particular object in the index. 76 77 @param {Object} object the item to search for 78 @param {Number} startAt optional starting location to search, default 0 79 @returns {Number} index of -1 if not found 80 */ 81 Array.prototype.lastIndexOf = function (object, startAt) { 82 var idx, len = this.length; 83 84 if (startAt === undefined) startAt = len - 1; 85 else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); 86 if (startAt < 0) startAt += len; 87 88 for (idx = startAt; idx >= 0; idx--) { 89 if (this[idx] === object) return idx; 90 } 91 return -1; 92 }; 93 } 94