Javascript add to line with every function call

I have the following situation when I have a function fthat takes an argument input.

I want to have fit satisfy the following conclusion:

f('l') --> fl

f() --> fo

f()('l') --> fol

f()()('l') --> fool

f()()()('l') --> foool

I thought it would be possible:

function f(input) {
  let str = 'f'
  if (input) {
    return `${str}${input}`
  }
  str = `${str}o`
  return f()
}

However, this ends with an endless loop. I also tried to have a freturn function, but this does not work either.

How can I write fto get the desired result while keeping the function idle?

+4
source share
4 answers

As I suggest to you in the comments, you are better off using generators to get each value after each call.

function * f(input) {
    for(const character of input) {
        yield character;
    }
}
test = f('hello world');
test.next(); // {value: "h", done: false}
test.next(); // {value: "e", done: false}
test.next(); // {value: "l", done: false}
test.next(); // {value: "l", done: false}
test.next(); // {value: "o", done: false}
test.next(); // {value: " ", done: false}
test.next(); // {value: "w", done: false}
test.next(); // {value: "o", done: false}
test.next(); // {value: "r", done: false}
test.next(); // {value: "l", done: false}
test.next(); // {value: "d", done: false}
test.next(); // {value: undefined, done: true}

, , . .

: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

0

function f(input) {
  let str = 'f'
  var o = function(suffix){
    if(suffix)
      return str + suffix;
    str += "o";
    return o;
  }
  return o(input);
}

console.log(f('l'))
console.log(f()('l'))
console.log(f()()('l'))
console.log(f()()()('l'))
Hide result
0

f() fo, . fo, f f()('').

:

function f(input, acc) {
    acc = acc || 'f'
    if (input === undefined) {
        return function(a) {
            return f(a, acc + 'o')
        }
    }
    return acc + input
}

console.log(f('l'))
console.log(f()(''))
console.log(f()('l'))
console.log(f()()('foo'))
Hide result
0

JS "" . , , .

const f = function _f(prefix){
  const toString = () => prefix;
  return Object.assign(function(suffix="o"){ 
    return _f(prefix + suffix);
  }, {
    valueOf: toString,
    toString
  });
}("f");

console.log(""+f('l'))
console.log(""+f())
console.log(""+f()('l'))
console.log(""+f()()('l'))
console.log(""+f()()()('l'))

let foo = f()();
let fool = foo("l");
console.log(""+foo("l"));
console.log(""+fool);
console.log(""+foo("bar"));
console.log(""+fool("bar"));
Hide result
0

Source: https://habr.com/ru/post/1691972/


All Articles