Skip to content

Instantly share code, notes, and snippets.

@Cerealkillerway
Last active December 3, 2015 11:59
Show Gist options
  • Save Cerealkillerway/cbf68ab8c24852f3f633 to your computer and use it in GitHub Desktop.
Save Cerealkillerway/cbf68ab8c24852f3f633 to your computer and use it in GitHub Desktop.
Useful js functions
// possible useful functions found on the web
//https://github.com/padolsey/string.prototype/blob/master/string.js
// left trim
String.prototype.ltrim = function () {
return this.replace(/^\s+/, '');
};
// right trim
String.prototype.rtrim = function () {
return this.replace(/\s+$/, '');
};
// replace inside a string
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
};
// dasherize string
String.prototype.dasherize = function() {
return this.replace(/\W+/g, "-").toLowerCase();
};
// capitalize string
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
// Array
// push into array if item does not alredy exists in it
Array.prototype.pushUnique = function (item){
if(this.indexOf(item) == -1) {
this.push(item);
return true;
}
return false;
};
// change item position inside an array
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
// insert element at index
Array.prototype.insertAt = function(element, index) {
this.splice(index, 0, element);
};
// delete element from index
Array.prototype.removeAt = function(index) {
this.splice(index, 1);
};
// get first element of array
Array.prototype.first = function() {
return this[0] || undefined;
};
// get last element of array
Array.prototype.last = function() {
if(this.length > 0) {
return this[this.length - 1];
}
return undefined;
};
// get max in array
Array.prototype.max = function(array){
return Math.max.apply(Math, array);
};
// get min in array
Array.prototype.min = function(array){
return Math.min.apply(Math, array);
};
// DATE
// go to midnight
Date.prototype.toMidnight = function(){
this.setMinutes(0);
this.setSeconds(0);
this.setHours(0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment