重构具有多个else if块的函数

m528fe3b  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(436)

我有以下功能,可以根据日期的月份设置日期点。但我正在硬编码这些值。我想重新考虑函数并删除多余的else if块。如我们所见,当天数减少一定值时,扣n-1分。那么,我如何重构它呢?

points = {}

function calcPointsForDates(createdTime) {

  let today = new Date()
  let Y = today.getFullYear()
  let M = today.getMonth()
  let T = today.getDate()

  let monthAgo = days => new Date(Y, M, T - days).getTime()

  if (createdTime > monthAgo(30)) {
    points.date = 2
  } else if (createdTime < monthAgo(180)) {
    points.date = -5
  } else if (createdTime < monthAgo(90)) {
    points.date = -4
  } else if (createdTime < monthAgo(60)) {
    points.date = -3
  } else if (createdTime < monthAgo(30)) {
    points.date = -2
  }
}
calcPointsForDates(post.created.getTime())
luaexgnf

luaexgnf1#

考虑具有点属性的点对象,这些点是可以用来实现与if…..块相同的逻辑的点的中断值,例如。

let days2points = {'30': 2, '60': -2, '90': -3, '180': -4, '1e10': -5};

通过在键上循环找到第一个天数(diff)小于键的值。然后使用它返回值,其中diff<30返回2,diff<60返回-2,等等。值“1e10”本质上表示无穷大,可以设置为number.max_safe_integer(9007199254740991天或大约24.6万亿年前)。
因此,获取今天和createddate之间的天数差,找到相关的键并返回点,例如。

function getPoints(createdTime) {
  // Create a points object for points related to days ago
  let days2points = {'30': 2, '60': -2, '90': -3, '180': -4, '1e10': -5}; 

  // Get the number of days between today and createdTime
  let diff = (new Date().setHours(0,0,0,0) - createdTime) / 8.64e7;

  // Find the relevant value in the points object
  let key = Object.keys(days2points).find(daysAgo => diff < daysAgo);

  // Debug
  console.log('Days ago: ' + diff + ' Value: ' + days2points[key]);

  // Return the value
  return days2points[key];
} 

// Examples
let d = new Date();
let [Y, M, D] = [d.getFullYear(), d.getMonth(), d.getDate()];
[ d,                        // today
  new Date(Y, M, D -   3),  //   3 days ago
  new Date(Y, M, D -  30),  //  30 days ago
  new Date(Y, M, D -  33),  //  33 days ago
  new Date(Y, M, D -  63),  //  63 days ago
  new Date(Y, M, D -  93),  //  93 days ago
  new Date(Y, M, D - 183)   // 183 days ago
].forEach(d => 
  console.log(d.toDateString() + ' => ' + getPoints(d))
);

上述用途 < 用于比较,使断点不包含在内,30天前返回-2。如果断点应包含在内,则进行比较 <= 或向断点添加1。
警告
计算差异的方法是近似的,有更好的方法。
object.keys中的对象属性不需要与用于创建Days2点的对象文字具有相同的顺序,因此在对它们进行迭代之前,应该严格地对它们进行排序。

qpgpyjmq

qpgpyjmq2#

您可以将限制和日期点添加到数组中,并从最低到最高迭代该数组。如果满足限制条件,则返回相应的日期点。如果不满足任何条件,则返回默认值。

const 
  datePoints = [
      [180, -5],
      [90, -4],
      [60, -3],
      [30, -2]
    ],
  defaultPoints = 2;

function daysAgo(d) {
  const now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), now.getDay() - d);
}

function getDatePoints(createdTime) {
  for (let d of datePoints) {
    if (createdTime < daysAgo(d[0]))
      return d[1];
  }

  return defaultPoints;
}

for (let i = 1; i < 200; i+= 10)
  console.log(i, daysAgo(i).toISOString(), getDatePoints(daysAgo(i)));

相关问题