PDA

View Full Version : Array insertAt, insertBefore, insertAfter



mabello
5 Jun 2008, 9:30 AM
Despite I don't like adding properties and functions to the prototype of native javascript object (you could have problems if you want to integrate different javascript libraries, as you probably have already face that issue), I have added some functionalities to the native javascript array.

The code explain itself ;)



Ext.applyIf(Array.prototype, {
/**
* Add an element at the specified index
* @param {Object} o The object to add
* @param {int} index The index position the element has to be inserted
* @return {Boolean} True if you can insert
*/
insertAt : function(o, index){
if ( index > -1 && index <= this.length ) {
this.splice(index, 0, o);
return true;
}
return false;
},
/**
* Add an element after another element
* @param {Object} The object before which you want to insert
* @param {Object} The object to insert
* @return {Boolean} True if inserted, false otherwise
*/
insertBefore : function(o, toInsert){
var inserted = false;
var index = this.indexOf(o);
if(index == -1)
return false;
else {
if(index == 0){
this.unshift(toInsert)
return true;
}
else
return this.insertAt(toInsert, index - 1);
}
},
/**
* Add an element before another element
* @param {Object} The object after which you want to insert
* @param {Object} The object to insert
* @return {Boolean} True if inserted, false otherwise
*/
insertAfter : function(o, toInsert){
var inserted = false;
var index = this.indexOf(o);
if(index == -1)
return false;
else {
if(index == this.length - 1){
this.push(toInsert);
return true;
}
else
return this.insertAt(toInsert, index + 1);
}
}
});



Example of use:


var a =[1,2,3];
a.insertAt('a', 1);

a.insertAfter(3, 'c');
a.insertBefore('a', 'b');
var t = a.join();
alert(t);


For a real usage example, check this out:
http://extjs.com/forum/showthread.php?p=178176#post178176

Keep up the good work with ext!

Jets
17 Aug 2008, 7:25 PM
:D

JorisA
19 Aug 2008, 2:41 AM
this is one I regularly use:


String.prototype.ucFirst = function () {
return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};

galdaka
19 Aug 2008, 8:15 AM
More...

http://extjs.com/forum/showthread.php?t=32799