if(!Array.indexOf){
Array.prototype.indexOf = function (obj) {
for (var i=0; i<this.length; i++) {
if (this[i] == obj) {
return i;
}
}
}
}
function range(begin, end, step){
var rangeArray = []
, rangeString = 'abcdefghijklmnopqrstuvwxyz';
if (Object.prototype.toString.call(begin) == '[object Number]') {
rangeArray[0] = begin;
step = step || 1;
while (begin + step <= end) {
rangeArray[rangeArray.length] = begin += step;
}
} else {
if (begin === begin.toUpperCase()){
end = end.toUpperCase();
rangeString = rangeString.toUpperCase();
}
rangeString = rangeString.substring(rangeString.indexOf(begin), rangeString.indexOf(end) + 1);
rangeArray = rangeString.split('');
}
return rangeArray;
}
console.log(range(0, 10));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(-100, 100, 20));
// [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100]
console.log(range('A', 'F'));
// ['A', 'B', 'C',' D', 'E', 'F')
console.log(range('m', 'r'));
// ['m', 'n', 'o', 'p', 'q', 'r']
function range (start, end, step) {
var range = []
, typeofStart = typeof start
, typeofEnd = typeof end;
if (step === 0) {
throw TypeError("Step cannot be zero.");
}
if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}
typeof step == "undefined" && (step = 1);
if (end < start) {
step = -step;
}
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}
start = start.charCodeAt(0);
end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}
} else {
throw TypeError("Only string and number types are supported");
}
return range;
}
console.log(range("a", "z", 1));
console.log(range("Z", "A", 1));
console.log(range("A", "Z", 3));
console.log(range(0, 25, 1));
console.log(range(0, 25, 5));
console.log(range(20, 5, 5));
Комментариев нет:
Отправить комментарий