选择一个相对于另一个数字的数字



有没有更好的方法(不需要速度,需要简洁和简单)可以在更少的代码行中实现以下功能?(以下示例)

//    Example //
/*
 * Get Divisor For Number of Iterations - To Display Progress
*/
int fGetDivisor(int iMaxIters) {  
  int iDiv = 500;   // init
  if (iMaxIters >= 100000)
    iDiv = 20000;
  else if (iMaxIters > 20000)
    iDiv = 10000;
  else if (iMaxIters > 5000)
    iDiv = 2000;
  else if (iMaxIters > 2000)
    iDiv = 1000;
  return iDiv;
}

使用a ? b : c:

int fGetDivisor(int iMaxIters) =>
    iMaxIters >= 100000 ? 20000 :
    iMaxIters >   20000 ? 10000 :
    iMaxIters >    5000 ?  2000 :
    iMaxIters >    2000 ?  1000 :
                            500 ;

或者用Map<int,int>只在一个地方有条件:

import 'dart:collection';
int fGetDivisor(int iMaxIters) {
  final map = new LinkedHashMap<int,int>()
    ..[99999] = 20000
    ..[20000] = 10000
    ..[ 5000] =  2000
    ..[ 2000] =  1000
    ;
  for (final step in map.keys) {
    if (iMaxIters > step) return map[step];
  }
  return 500;
}

坦率地说,我认为那些firstWhere使它变得更加复杂。

这是我能想到的最简单的:

int fGetDivisor(int iMaxIters) {
  if (iMaxIters >= 100000) return 20000;
  if (iMaxIters > 20000) return 10000;
  if (iMaxIters > 5000) return 2000;
  if (iMaxIters > 2000) return 1000;
  return 500;
}

通常对于这种类型的代码,我喜欢使用键列表和值列表。第一个Where方法也能帮助我们:

int fGetDivisor(int iMaxIters) {
  var keys = [99999, 20000, 5000, 2000];
  var vals = [20000, 10000, 2000, 1000];
  var key = keys.firstWhere((e) => iMaxIters > e, orElse: () => null);
  return key == null ? 500 : vals[keys.indexOf(key)];
}

这种方法还可以轻松地添加新的值进行检查。

int fGetDivisor(int iMaxIters) =>
  [[999999, 20000], [20000, 10000], [5000, 2000], [2000, 1000]]
    .firstWhere((x) => iMaxIters > x[0], orElse: () => [0, 500])[1];

最新更新