如何在JavaScript中将参数传递给compose函数中的每个函数

时间:2019-04-30 06:16:32

标签: javascript function functional-programming

我要编写两个函数。

第一个函数需要两个参数。第一个参数是日期,第二个参数是日期的格式化程序。如下所示:

/*
  Definition of date formats below:
  LTS  : 'h:mm:ss A',
  LT   : 'h:mm A',
  L    : 'MM/DD/YYYY',
  LL   : 'MMMM D, YYYY',
  LLL  : 'MMMM D, YYYY h:mm A',
  LLLL : 'dddd, MMMM D, YYYY h:mm A'
  Pass these into the second parameter of the formatDate function to return the expected date format
 */
export const formatDate = (date = moment(), F = "L") => moment(date).format(F); // F means format refer to the comment above before the function L is the default argument

第二个功能也需要两个参数。第一个参数是日期,第二个参数是要在日期中添加的月份数。如下所示:

export const addMonth = (date = moment(), amount) => moment(date).add(amount, 'months');

现在,当我使用jest一起测试这两个功能时。

 expect(
    Util.formatDate(
      Util.addMonth(
        new Date('December 17, 1995 03:24:00'), 1,
      ),
    ),
  ).toEqual("01/17/1996");

现在测试用例已经通过,所以一切似乎都可以正常工作。

现在,我想使用 compose 函数,该函数构成函数调用并接受参数并传递主参数以返回最终结果。

我发现这个link可以帮到我。

并在下面提出了以下代码:

const compose = (...functions) => args => functions.reduceRight((arg, fn) => fn(arg), args);

// Actual test case below:
 expect(
    compose(
      Util.formatDate,
      Util.addMonth,
    )(new Date('February 28, 2018 03:24:00')),
  ).toEqual("03/28/2018");

如何在compose函数内部的那些函数调用中传递每个 必需参数 。如下所示:

 expect(
    compose(
      (Util.formatDate, "L"),
      (Util.addMonth, 1),
    )(new Date('February 28, 2018 03:24:00')),
  ).toEqual("03/28/2018");

如果有更好的实现方法,可以告诉我。我是否需要使用一些库才能实现此目的?

感谢某人是否可以提供帮助 预先感谢。

1 个答案:

答案 0 :(得分:2)

要执行此操作,您需要使用函数并翻转参数顺序,因为计算通常需要相反​​的顺序:

// reusable combinators

const flip = f => y => x => f(x) (y);
const curry = f => x => y => f(x, y);
const comp = (f, g) => x => f(g(x));

// your functions

const formatDate = (x, y) => `formatDate(${x}, ${y})`;
const addMonth = (x, y) => `addMonth(${x}, ${y})`;

// your functions transformed to be compliant with function composition

const formatDate_ = flip(curry(formatDate));
const addMonth_ = flip(curry(addMonth));

// shows the computational structure

console.log(
  comp(
    formatDate_("F"),
    addMonth_("amount"))
      ("date")); // formatDate(addMonth(date, amount), F)

现在,您可以看到curring带来的好处:简单的功能组合和免费的部分应用程序。