Skip to content

Instantly share code, notes, and snippets.

@tytskyi
Last active August 29, 2015 14:06
Show Gist options
  • Save tytskyi/d2e8a4543bdbd484deeb to your computer and use it in GitHub Desktop.
Save tytskyi/d2e8a4543bdbd484deeb to your computer and use it in GitHub Desktop.
/**
* Get position of given element in array or given sub-string in string
*
* @raram {String|Array} source
* @param {String|Number|Boolean} term
*
* @return {Number} Position of term in source or -1
*/
var indexOf = (function () {
var NEGATIVE = -1;
var isArray = Array.isArray || function (source) {
return Object.prototype.toString.call(source) === '[object Array]';
};
var isString = function (source) {
return Object.prototype.toString.call(source) === '[object String]';
};
var handleArray = function (source, term) {
for (var i = 0, len = source.length; i < len; i++) {
if (source[i] === term) {
return i;
}
}
return NEGATIVE;
};
return function (source, term) {
if (isArray(source)) {
return source.indexOf ? source.indexOf(term) : handleArray(source, term);
} else if (isString) {
return source.indexOf(term);
}
return NEGATIVE;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment