Javascript add to string with each function call

后端 未结 5 2397
执念已碎
执念已碎 2020-12-21 05:32

I have the following situation where I have a function f which takes an argument input.

I want to be able to have f such that

5条回答
  •  猫巷女王i
    2020-12-21 06:08

    As I suggest you in comments, you should better use 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}
    

    As this, you just have to call the next function each time you need and concatenate the result.value each time.

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

提交回复
热议问题