es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

Suggest `sequence` function

Open jiwooproity opened this issue 1 year ago • 1 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"
})();

jiwooproity avatar Aug 18 '24 08:08 jiwooproity

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.

raon0211 avatar Aug 20 '24 13:08 raon0211

@raon0211 Thank you for review to my suggest. I agree to your think too after read your review comment. And I Sorry! but I'll get back to you when I think of a better way to contribute. Thank you for your kindly, i'm rooting for you.

jiwooproity avatar Aug 22 '24 12:08 jiwooproity