Created
March 18, 2010 16:34
-
-
Save StanAngeloff/336537 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
__slice = function __slice(source, start, end, step) { | |
var length, result, stringify; | |
if (!(typeof source !== "undefined" && source !== null)) { | |
throw "'source' cannot be empty when calling __slice(>> " + source + " <<, " + start + ", " + end + ", " + step + ")"; | |
} else if (step === 0) { | |
throw "'step' cannot be zero when calling __slice(..., " + start + ", " + end + ", >> " + step + " <<)"; | |
} | |
if (Object.prototype.toString.call(source) !== "[object Array]") { | |
source = source.toString().split(""); | |
stringify = true; | |
} | |
length = source.length; | |
start = (typeof start !== "undefined" && start !== null) ? (start < 0 ? start + length : start) : 0; | |
start < 0 ? (start = 0) : null; | |
end = (typeof end !== "undefined" && end !== null) ? (end < 0 ? end + length : end) : length; | |
end < 0 ? (end = start) : end > length ? (end = length) : null; | |
if (start === end) { | |
result = []; | |
} else { | |
step = (typeof step !== "undefined" && step !== null) ? step : (start <= end ? 1 : -1); | |
if (step === 1) { | |
result = Array.prototype.slice.call(source, start, end); | |
} else if (step === -1) { | |
result = Array.prototype.reverse.call(Array.prototype.slice.call(source, start, end)); | |
} else { | |
result = []; | |
while (step > 0 ? start < end : start > end) { | |
result.push(source[start]); | |
start = start + step; | |
} | |
} | |
} | |
return (stringify ? result.join("") : result); | |
}; | |
console.log(__slice("hello, world", 3, 5)); // 'lo' | |
console.log(__slice("hello, world", 10)); // 'ld' | |
console.log(__slice("hello, world", null, null, -1)); // 'dlrow ,olleh' | |
console.log(__slice("hello, world", -11, -7, -1)); // 'olle' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment