Skip to content

Instantly share code, notes, and snippets.

@joshrhoades
Created May 2, 2013 17:28
Show Gist options
  • Save joshrhoades/5503843 to your computer and use it in GitHub Desktop.
Save joshrhoades/5503843 to your computer and use it in GitHub Desktop.
Common and useful Prototype Shims
/**
* SHIM to add `Date.now` functionality if it is not available, based off of EcmaScript 5.
* The `Date.now()` function returns a `number` value that is the time value designating the UTC date and time of the occurrence of the call to `now`.
* @see {@link http://es5.github.com/#x15.9.4.4}
* @global
* @method
* @name Date.now
* @example var dtNow = Date.now();
* @returns {date} Number value that is the time value designating the UTC data dn time of the time of the call to this
*/
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
/**
* Dom Helper that defines 'getElementsByClassName' for older browsers that don't support this method. This uses Dustin Diaz' pure DOM method implementation.
* @param {string} searchClass the CSS Class (string) to search elements for
* @example var domResults = document.getElementsByClassName('mySuperSweetClassName');
* @example
var domResults = document.getElementsByClassName('mySuperSweetClassName');
if (domResults && domResults.length > 0) {
//now we can loop through the results or do changes on the returned data set
}
* @method
* @global
* @see {@link http://ejohn.org/blog/getelementsbyclassname-speed-comparison/}
* @returns {array} Array of any DOM Elements with the specific `searchClass` argument. Length of return is 0 if no matches/elements found
*/
if (typeof document.getElementsByClassName !== 'function') {
document.getElementsByClassName = function(searchClass) {
var classElements = [];
var els = document.getElementsByTagName('*');
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
};
}
/**
* Extension to add `array.contains` global shim to extend the array prototype
* @example [1, 2, 3].contains(2);//returns true
* @example [1, 2, 3].contains('2');//returns false
* @global
* @method
* @returns {boolean} Returns `true` if the array contains the item, otherwise returns `false`
*/
if (typeof Array.prototype.contains !== 'function') {
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
}
/**
* Add Remove to javaScript native array function, to remove specific named elements within array
* @global
* @method
* @example myArray.remove(1,0)
* @example ['one','two','three'].remove('two');//results in ['one','three']
* @example
var arrExample = ['one','two','three'];
arrExample = arrExample.remove('two');//results in ['one','three']
* @returns {array} Returns passed in array with any array positions specified removed
*/
if (typeof Array.prototype.remove !== 'function') {
Array.prototype.remove = function() {
var what, a = arguments,
L = a.length,
ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
}
};
/**
* Extends JavaScript Native to add `.startsWith()` to the `string` `prototype` if it is not already defined/available to the browser.
* Note that this is case-sensitive.
* @global
* @method
* @param {string} str - String to check for a starting match
* @see endsWith
* @example 'Hello World!'.startsWith('He');//returns true
* @example
var strMyString = 'Lorem Ispum Marblehead Faces'
, strMatch = 'BLUEY!';
if ((strMyString).startsWith(strMatch)) {
//returns false, no match, would not execute
} else {
//this would execute, starts match
}
* @returns {boolean} `true` if string starts with the provided argument check, `false` if string DOES NOT start with the provided argument check
*/
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function(str) {
return this.slice(0, str.length) == str;
};
}
/**
* Extends JavaScript Native to add `.endsWith()` to the `string` `prototype` if it is not already defined/available to the browser.
* Note that this is case-sensitive.
* @global
* @method
* @param {string} str - String to check for a starting match
* @see startsWith
* @example 'Hello World!'.endsWith('TIMMY!');//returns false
* @example
var strMyString = 'Lorem Ispum Marblehead Faces'
, strMatch = 'BLUEY!';
if ((strMyString).endsWith(strMatch)) {
//returns false, no match, would not execute
} else {
//this would execute, endings match
}
* @returns {boolean} `true` if string ends with the provided argument check, `false` if string DOES NOT end with the provided argument check
*/
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(str) {
return this.slice(-str.length) == str;
};
}
/**
* Create trim function for browsers that don't support trimming trailing and leading whitespace, such as <= IE8
* @global
* @example var strTrim = ' 4 spaces before, 8 spaces after '.trim();//strTrim == '4 spaces before, 8 spaces after'
* @example
var trimTestBefore = ' 4 spaces before, 8 spaces after '
, trimTestAfter = '4 spaces before, 8 spaces after';
if (trimTestBefore.trim() == trimTestAfter) {
//true, execute
}
* @method
* @returns {string} Returns string with leading/trailing whitespace removed
*/
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
};
/**
* Global EcmaScript 5 shim to extend JavaScript Natives to add the `isArray` functionality to Array operations for browsers that do not support it. If `isArray` exists,
* this function will pass through by default without adding overhead
* @global
* @method
* @see {@link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray}
* @param {array} arrCheck - Alleged array object to check
* @example if (Array.isArray(['one','two','three'])) { ... }
* @example bIsArray = Array.isArray(myArr);
* @returns {boolean} TRUE If object toString type == `[object Array]`
* @returns {boolean} FALSE If object toString type != `[object Array]`
*/
if (typeof(Array.isArray) !== 'function') {
Array.isArray = function isArray(arrCheck) {
return Object.prototype.toString.call(arrCheck) == '[object Array]';
};
};
/**
* Create Array.indexOf if not natively available
* @param {string} val The value indexOf is checking against
* @returns {number} The index of the first occurrance of val, based on the supplied Array.
* @example ['one','two','three'].indexOf('three'); //outputs 2
* @global
* @name indexOf
* @method
*/
if (typeof(Array.prototype.indexOf) !== "function") {
Array.prototype.indexOf = function(val) {
for (var i = 0, len = this.length; i < len; i++) {
if (val === this[i]) {
return i;
}
}
return -1;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment