为数字和数组编写了一个异常函数。一切正常,但问题是代码对于这样的功能来说太大了。你如何优化(减少)这个功能?
(function() {
$.random = function(int__min, int__max, exceptions, tof__integer) {
if (int__min instanceof Array) {
var int__min_length = int__min.length - 1,
arr_exceptions = null;
if (int__max instanceof Array) {
arr_exceptions = [];
$.each(int__max, function(idx, el) {
arr_exceptions[arr_exceptions.length] = int__min.indexOf(el);
});
} else {
arr_exceptions = int__min.indexOf(int__max);
};
return int__min[$.random(0, int__min_length, arr_exceptions, true)];
} else if (typeof int__min === 'number' && typeof int__max === 'number') {
if (!int__min) int__min = 0;
if (!int__max) int__max = 10;
if (int__min > int__max) {
var int__min_val = int__min,
int__max_val = int__max;
int__min = int__max_val;
int__max = int__min_val;
};
var int__random = null;
if (tof__integer === undefined || tof__integer === true) {
int__random = Math.floor(Math.random() * (int__max + 1 - int__min) + int__min);
} else {
int__random = Math.random() * (int__max + 0.1 - int__min) + int__min;
};
if (typeof exceptions === 'number' || typeof exceptions === 'string') {
if (exceptions !== int__random) {
return int__random;
} else {
return $.random(int__min, int__max, exceptions, tof__integer);
};
} else if (exceptions instanceof Array) {
var tof__resolution = true;
$.each(exceptions, function(idx, el) {
if (int__random === el) tof__resolution = false;
});
if (tof__resolution) {
return int__random;
} else {
return $.random(int__min, int__max, exceptions, tof__integer);
};
} else {
return int__random;
};
} else {
console.error('UARR.RANDOM: Invalid values!');
};
};
})();
(function() {
console.log( $.random( 0, 10, null, false ) );
console.log( $.random( 0, 10, null, true ) );
console.log( $.random( 0, 10, [5, 6, 7, 8] ) );
console.log( $.random( ['a', 'b', 'c'], 'a' ) );
console.log( $.random( ['a', 'b', 'c'], ['a', 'c'] ) );
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
对于数字:
$.random( a, b, c, d );
a - Минимальное число
b - Максимальное число
c - Исключения (число, которое не нужно показывать. Можно указывать массивом)
d - Целые числа или нет (true/false)
对于数组:
$.random( a, b );
a - Массив данных
b - Исключения (значения, которые не нужно показывать. Можно указывать массивом)
并非所有案例都清楚(例如,这个有点伤我的脑筋-
console.log( $.random( 0, 10, [5, 6, 7, 8] ) );
例外有什么意义?
但在这里我做到了,两倍短而且没有骑师: