toss/es-toolkit

Suggest `sequence` function

jiwooproity opened this issue · 2 comments

How about this sequence function?
Use generator to implements sequence function, it can run function in sequence.

I'm thinking of a sequence function that can be executed sequentially.

For example

function sequence<F extends (args: any) => any>(funcs: F[]) {
  const generator = (function* () {
    for (let i = 0; i < funcs.length; i++) {
      yield funcs[i];
    }
  })() as Generator<F>;

  return (args?: any) => {
    const result = generator.next() as IteratorResult<F>;
    return result.done ? undefined : result.value(args);
  };
}
(() => {
  const seq = sequence([console.log, () => console.log("hi")]);

  seq("hello"); // console: "hello"

  seq(); // console: "hi"
})();

Hello, @jiwooproity :) Thanks for your suggestion!

I guess this could be easily implemented in modern JavaScript, and I think there is limited usecase for this function. This might be out-of-scope of es-toolkit.