Created
February 2, 2012 17:59
-
-
Save aurels/1724876 to your computer and use it in GitHub Desktop.
JS must have
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
if(typeof console === "undefined") { | |
console = { log: function() { } }; | |
} | |
// Reduce | |
if (!Array.prototype.reduce) | |
{ | |
Array.prototype.reduce = function(fun /*, initial*/) | |
{ | |
var len = this.length >>> 0; | |
if (typeof fun != "function") | |
throw new TypeError(); | |
// no value to return if no initial value and an empty array | |
if (len == 0 && arguments.length == 1) | |
throw new TypeError(); | |
var i = 0; | |
if (arguments.length >= 2) | |
{ | |
var rv = arguments[1]; | |
} | |
else | |
{ | |
do | |
{ | |
if (i in this) | |
{ | |
var rv = this[i++]; | |
break; | |
} | |
// if array contains no values, no initial value to return | |
if (++i >= len) | |
throw new TypeError(); | |
} | |
while (true); | |
} | |
for (; i < len; i++) | |
{ | |
if (i in this) | |
rv = fun.call(undefined, rv, this[i], i, this); | |
} | |
return rv; | |
}; | |
} | |
// Trim | |
function trim(s) { | |
return ( s || '' ).replace( /^\s*|\s*$/g, '' ); | |
}; | |
String.prototype.trim = function(){ | |
return trim(this); | |
}; | |
// Truncate | |
function truncate(string, length) { | |
if (string.length > length) { | |
return string.slice(0, length - 3) + "..."; | |
} else { | |
return string; | |
} | |
}; | |
String.prototype.truncate = function(length){ | |
return truncate(this, length); | |
}; | |
// Camelize | |
String.prototype.camelize = function(){ | |
return this.replace(/(?:^|[-_])(\w)/g, function (_, c) { | |
return c ? c.toUpperCase () : ''; | |
}); | |
}; | |
String.prototype.camelizeVar = function(){ | |
var camelized = this.camelize(); | |
var firstLetter = camelized[0].toLowerCase(); | |
return camelized.replace(/^./, firstLetter); | |
}; | |
// Array intersection | |
Array.prototype.contains = function(elem) { | |
return(this.indexOf(elem) > -1); | |
}; | |
Array.prototype.intersect = function( array ) { | |
// this is naive--could use some optimization | |
var result = []; | |
for ( var i = 0; i < this.length; i++ ) { | |
if ( array.contains(this[i]) && !result.contains(this[i]) ) | |
result.push( this[i] ); | |
} | |
return result; | |
}; | |
// Prepend http://jsfiddle.net/fUcEr/ (VDTonton) | |
Array.prototype.prepend = function(item){ | |
this.splice(0, 0, item); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment