Last active
August 29, 2015 14:06
-
-
Save tytskyi/d2e8a4543bdbd484deeb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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