Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active October 2, 2015 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlun78/2158512 to your computer and use it in GitHub Desktop.
Save marlun78/2158512 to your computer and use it in GitHub Desktop.
Some Array util methods.
/*!
* Array Extras, version 1.0
* Copyright (c) 2012, marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* Depends on type.extras.js
*/
(function(ns){
// Returns the first index at which a given type can be found in the array, or -1 if it is not present.
var indexOfType = function (array, type, fromIndex) {
if (!ns.isArray(array)) { throw new TypeError(/*'indexOfType() first argument must be of type Array.'*/); }
if (!ns.isString(type)) { throw new TypeError(/*'indexOfType() second argument must be of type String.'*/); }
type = type.toLowerCase();
var index = ns.isNumber(fromIndex) ? fromIndex : 0,
length = array.length;
while (index < length) {
if (typeOf(array[index]) === type) { return index; }
index += 1;
};
return -1;
};
// Returns the last index at which a given type can be found in the array, or -1 if it is not present.
var lastIndexOfType = function (array, type, fromIndex) {
if (!ns.isArray(array)) { throw new TypeError(/*'lastIndexOfType() first argument must be of type Array.'*/); }
if (!ns.isString(type)) { throw new TypeError(/*'lastIndexOfType() second argument must be of type String.'*/); }
type = type.toLowerCase();
var index = ns.isNumber(fromIndex) ? Math.min(array.length, fromIndex) : array.length;
while (index > 0) {
index -= 1;
if (ns.typeOf(array[index]) === type) { return index; }
};
return -1;
};
// Returns the first element of a given type in the array, or null if none is present.
ns.elementOfType = function (array, type, fromIndex) {
var index = indexOfType(array, type, fromIndex);
return index !== -1 ? array[index] : null;
};
// Returns the last element of a given type in the array, or null if none is present.
ns.lastElementOfType = function (array, type, fromIndex) {
var index = lastIndexOfType(array, type, fromIndex);
return index !== -1 ? array[index] : null;
};
// Converts an arguments object to a real Array.
ns.toArray = function (argumentsObject) {
return Array.prototype.slice.call(argumentsObject);
};
// Expose methods
ns.indexOfType = indexOfType;
ns.lastIndexOfType = lastIndexOfType;
}(window.APP));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment