Created
September 11, 2013 06:16
-
-
Save davidlonjon/6519907 to your computer and use it in GitHub Desktop.
JavaScript: Additional Array Prototypes
This file contains 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
/** | |
* Remove value(s) from an array | |
* | |
* @return {array} Modified array | |
*/ | |
if (typeof Array.prototype.remove == 'undefined' | |
|| typeof Array.prototype.remove == null) { | |
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; | |
}; | |
} | |
/** | |
* Remove one occurence of value(s) from an array | |
* | |
* @return {array} Modified array | |
*/ | |
if (typeof Array.prototype.removeOneOccurence == 'undefined' | |
|| typeof Array.prototype.removeOneOccurence == null) { | |
Array.prototype.removeOneOccurence = function() { | |
var what, a = arguments, L = a.length, ax; | |
while (L && this.length) { | |
what = a[--L]; | |
if ((ax = this.indexOf(what)) !== -1) { | |
this.splice(ax, 1); | |
} | |
} | |
return this; | |
}; | |
} | |
/** | |
* Count the number of occurences for a specific value in an array | |
* | |
* @param {string} value Value | |
* | |
* @return {integer} The number of occurences | |
*/ | |
if (typeof Array.prototype.countOccurrences == 'undefined' | |
|| typeof Array.prototype.countOccurrences == null) { | |
Array.prototype.countOccurrences = function(value) { | |
var count = 0; | |
for (var i = 0, j = this.length; i < j; i++) { | |
if (this[i] == value) { | |
count++; | |
} | |
} | |
return count; | |
}; | |
} | |
/** | |
* Check if a there is only one value (and its occurences) in an array | |
* | |
* @param {string} value Value | |
* | |
* @return {boolean} Whether or not the value (and its occurences) is the only one in the array | |
*/ | |
if (typeof Array.prototype.checkOnly == 'undefined' | |
|| typeof Array.prototype.checkOnly == null) { | |
Array.prototype.checkOnly = function(value) { | |
var occurencesCount = 0; | |
for (var i = 0, j = this.length; i < j; i++) { | |
if (this[i] == value) { | |
occurencesCount++; | |
} | |
} | |
if (occurencesCount == this.length) { | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment