有没有更简洁的方法来为数组分析器编写这个JavaScript代码?

时间:2016-02-05 07:12:27

标签: javascript arrays

我一直在解决一些问题和挑战,我想知道你是否愿意给我一些反馈和一些帮助。挑战是编写一个阵列分析器,输出平均值,中位数,负数和奇数值。我有一个很长的版本,我试图重构,并发现了一个发现中位数的泡菜。这是长版本。

var Analyzer = {};

Analyzer.analyze = function(array){
var results = {};
var numbers = array.split(',').map(Number);

results.odds = Analyzer.odds(numbers);
results.negatives = Analyzer.negatives(numbers);
results.avg = Analyzer.avg(numbers);
results.median = Analyzer.median(numbers);

return results;
};

Analyzer.odds = function(e){
var odds = 0;

args.map(function(value){
    if(value % 2 !== 0)
        odds++;
});

return odds;
};

Analyzer.negatives = function(e){
var negatives = 0;

args.map(function(value){
    if(value < 0)
         negatives++;
 });

return negatives;
};

Analyzer.avg = function(e){
var total = 0;

args.map(function(value){total+=value});

var avg = total/args.length;

return avg !== undefined ? parseFloat(avg.toFixed(2)) : 0;
};

Analyzer.median = function(e){
var sortable = args;
sortable.sort(function(a,b){return a-b;});

var middle = Math.floor(sortable.length/2);    

return sortable.length % 2 ? sortable[middle] : (sortable[middle-1] +         sortable[middle]) /2;
};

这是简短版本

function arrayAnalyzer() {
  var results = {
    odds: 0,
    negatives: 0,
    avg: 0,
    median: 0
  }
 for (var i = 0; i < arguments.length; i++) {
  if (Math.abs(arguments[i]) % 2 === 1) results.odds++
    if (arguments[i] < 0)
    results.negatives++
    results.avg += arguments[i] / arguments.length
    results.median = (arguments.length - 1) / 2 #this is just me getting lucky with the output. It doesn't solve! 

}
console.log(results);

}

arrayAnalyzer(7, -3, 0, 12, 44, -5, 3); #testcase

0 个答案:

没有答案