Vanilla Javascript算法,如何做和解释

Vanilla Javascript algorithm, how to do it and explanation

本文关键字:何做 解释 Javascript 算法 Vanilla      更新时间:2023-09-26

对于我的学校作业,我必须编写一个名为的纯Javascript函数

foo(c)

应该返回以下值:

foo('a')  // return 'fa'
foo()('b')  // return 'fob'
foo()()("t"))  // return 'foot'

因此,基本上,当用字符"c"作为参数调用函数时,会返回整个值(请注意,调用foo()会在整个返回值中添加一个"o"字符,并且最终字符串返回的第一个字符总是"f"。

有人能提供一个可能的实施方案吗?理想情况下,我想自己尝试,所以也最欢迎提示和提示,以及代码中的注释。

NB:我目前最大的困难是找到一种连接调用函数的方法。

谢谢。

这里有一个带有箭头函数的递归方法:

const foo = c => {
    let rec = acc => x => x === undefined ? rec(acc + "o") : foo(acc + x);
    return c === undefined ? rec("o") : "f" + c;
};
foo('t'); // "ft"
foo()('t'); // "fot"
foo()()('t'); // "foot"

foo是一个一元函数,但当它在没有任何参数的情况下被调用时,它可以处理这种情况。内部函数rec以curried形式定义,并接受累加器作为其第一个参数,接受字符串作为其第二个参数。每当省略第二个参数时,rec就会递归地调用自己。

function foo ( c ) {
  // Initialize the result
  var result = 'f';
  // Call the internal foo and return the result
  // Which will either be the function itself, or a string, depnding on 
  // whether or not a truthy argument was passed in
  return foo( c );
  function foo ( c ) {
      // If an argument was passed in, return the result
      if ( c )
          return result + c;
      // Otherwise append an 'o' to the result
      result += 'o';
      // and return the function so it can be called again
      return foo;
  }
}

Iven的回答激励我接受这个有趣的挑战

// ES6
const foo = (x,y='f') => x && (y + x) || (x => foo(x, y + 'o'));
foo('a'); // "fa"
foo()('b'); // "fb"
foo()()('t'); // "foot"

对于仍在使用ES5…的人

// ES5
var foo = function foo(x) {
  var y = arguments.length <= 1 || arguments[1] === undefined ? 'f' : arguments[1];
  return x && y + x || function (x) {
    return foo(x, y + 'o');
  };
};
foo('a'); // "fa"
foo()('b'); // "fb"
foo()()('t'); // "foot"

如果你不能想出像@Iven Marquardt这样的绝妙想法,那么一个闭包就可以完美地完成任务。

function Foo(){
  var count = 0,
        str = "";
  function f(a){
    if (!!a){
    str = "f"+"o".repeat(count)+a;
    count = 0;
    return str;
    }
  count++;
  return foo;
  }
  return f;
}
var foo = Foo();
foo('a')       // <- 'fa'
foo()('b')     // <- 'fob'
foo()()("t"))  // <- 'foot'

除了我之前的答案之外,我还想单独添加一个答案,因为我不想让这个漂亮的答案被忽视。问题是,这个问题最合适的解决方案可能在于ES6默认值的一个被忽视的特性。

调用函数时,如果未提供具有默认值的参数,则应用其默认值(它不会变成"未定义")

一旦你知道了这个功能,这个问题的答案就非常简单了,只不过是一句话。

var foo = (c, o = "") => !!c ? "f"+o+c : c => foo(c, o+= "o")
foo("a");    //fa
foo()("b");  //fob
foo()()("t") //foot