如何使这个程序JS更具功能性?

时间:2015-04-02 07:02:43

标签: javascript functional-programming

鉴于此功能可根据用户设置重新排序数组...

function getDayNamesInUserOrder() {

    var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var weekStartDayIndex = 2; // user has set this to be 2 (Tuesday)

    // remove the first n days from the front of the array...
    var daysSlicedFromStart = dayNames.splice(0, weekStartDayIndex);

    // and stick them onto the end of it.
    var dayNamesInUserOrder = dayNames.concat(daysSlicedFromStart);

    return dayNamesInUserOrder;
}

getDayNamesInUserOrder();
=> ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon']

在使用较少的状态和变量时,如何使其更具功能性?

3 个答案:

答案 0 :(得分:2)

这个怎么样?

function getDayNamesInUserOrder(offset) {
  var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  return [0,1,2,3,4,5,6].map(function (i) {
    return dayNames[(i+offset) % 7];
  });
}

答案 1 :(得分:0)

你可以这样做:

function getDayNamesInUserOrder(startIndex) {
    var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var result = [];
    for (var i = 0; i < dayNames.length; i++) {
        result.push(dayNames[(startIndex + i) % dayNames.length]);
    }
    return result;
}

演示:http://jsfiddle.net/jfriend00/ddhagb33/


仅供参考,似乎很难找到“功能性编程”的清晰定义。我能找到的是:

  1. 数据应该是不可变的 - 如果您需要修改后的数据版本,则需要创建新的修改后的副本
  2. 函数应该是无状态的(没有影响将来调用同一函数的副作用)
  3. 此功能满足这两个要求(与原始功能一样)。如果你有一个更具体的“更具功能性”的愿望,那么请准确描述你所追求的目标。

答案 2 :(得分:-1)

function getDayNamesInUserOrder() {
  var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  var weekStartDayIndex = 2; // user has set this to be 2 (Tuesday)

  return dayNames.concat(dayNames).slice(weekStartDayIndex, weekStartDayIndex + 7);
}