Skip to content

Instantly share code, notes, and snippets.

@ian-plosker
Created April 12, 2011 18:24
Show Gist options
  • Select an option

  • Save ian-plosker/916084 to your computer and use it in GitHub Desktop.

Select an option

Save ian-plosker/916084 to your computer and use it in GitHub Desktop.
The beginning of a standard library for javascript
/* The beginning of a standard library */
Array.prototype.indexOf = function (obj, pos, compareFn) {
var pos = pos || 0;
compareFn = compareFn || function(obj1, obj2) { return obj1 == obj2; };
for (; pos < this.length; pos++) {
if (compareFn(obj, this[pos])) { return pos; }
}
return -1;
};
Array.prototype.lastIndexOf = function (obj, pos) {
var pos = pos || this.length - 1;
for (; pos >= 0; pos--) {
if (obj === this[pos]) { return pos; }
}
return -1;
};
Array.prototype.add = function () {
var i = 0;
for (; i < arguments.length; i++) {
if (this.indexOf(arguments[i]) === -1) { this.push(arguments[i]); }
}
};
Array.prototype.remove = function (obj) {
var index;
while ((index = this.indexOf(obj)) !== -1) {
this.splice(index, 1);
}
return this;
};
Object.size = function (obj, includeFns) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key) && (!includeFns || typeof obj[key] == 'function')) { size++; }
}
return size;
};
Object.toArray = function (obj) {
var coll = [], key;
for (key in obj) {
if (obj.hasOwnProperty(key) && typeof obj[key] !== 'function') {
coll.push({ key: key, value: obj[key] });
}
}
return coll;
};
Object.isType = function (obj, type) {
return (obj.constructor === type);
}
String.prototype.format = function () {
var formatted = this, i = 0, regexp;
for (; i < arguments.length; i++) {
regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment