首页 > 解决方案 > 如何制作高阶函数来处理其他函数并使它们可被递归`while`函数使用?

问题描述

所以我有这些功能:


/**
 * @description Recurses while a condition is true. Not stack-safe.
 * @param {Object} object_arguments - Contains the arguments for the function.
 * @param {function} object_arguments.object_function - The function to execute.
 * @param {any[]} object_arguments.array_arguments - The arguments to pass to the function.
 * @param {boolean} object_arguments.boolean_condition - The condition that must be met for another recursion to occur.
 * @returns {any} The output after all the recursions.
 */
const any_while = ({
  object_function: f,
  array_arguments: a,
  boolean_condition: c,
}) => {
  if (c) {
    const object_output = f(...a);
    return any_while({
      object_function: object_output.object_function,
      array_arguments: object_output.array_arguments,
      boolean_condition: object_output.boolean_condition,
    });
  } else {
    return f(...a).any_output;
  }
};

const integer_increment = (integer) => integer + 1;

我想要另一个函数,让我们称之为它function_convert_for_while,它接受任何函数,在这种情况下integer_increment,并输出另一个函数,该函数可以用作函数的object_function参数any_while,并且可能还必须接受一些其他参数来设置条件。所以输出的函数function_convert_for_while应该输出一个形状如下的对象:

{
  object_function,
  array_arguments,
  boolean_condition,
  any_output
}

object_function“转换后的”函数在哪里,“array_arguments”包含下一次递归中转换后的函数的参数any_whileboolean_condition是停止/继续条件,any_output是所有递归后的最终输出。

我很难想象function_convert_for_while应该如何,尤其是它如何处理boolean_condition变量,因为它应该根据any_output每次递归后的值而改变。我在想也许我需要另一个函数来接受any_output变量并进行某种比较?但我不太确定。抱歉,如果这有点不连贯,请告诉我是否应该更好地解释任何事情,以及是否有更好的方法来完成我想要实现的目标。我真的很感激任何帮助,谢谢。

标签: javascriptrecursionfunctional-programminghigher-order-functions

解决方案


推荐阅读