Created
April 12, 2011 18:24
-
-
Save ian-plosker/916084 to your computer and use it in GitHub Desktop.
The beginning of a standard library for javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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