public
Last active

JS must have

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
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);
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.