dimanche 22 janvier 2023

JS function chaining/piping around non-objects - what is the most elegant pattern? [closed]

Let's imagine you have a number of separate functions that accept a string variable as an argument and return it with some modifications for further use. What is the most simple and elegant pattern to chain the function calls around a single variable in vanilla JavaScript you prefer and recommend to use in production?

  1. Function sandwich aka nested madness (straightforward, but not nice, poor readability):

    let str = 'random text';
    str = func4(func3(func2(func1(str))));
    
  2. Copy-paste method (simple, readable, but repetitive):

    let str = 'random text';
    str = func1(str);
    str = func2(str);
    str = func3(str);
    str = func4(str);
    
  3. Array juggling (feels goods and automated, but not super neat):

    let str = 'random text';
    [func1, func2, func3, func4].forEach((func) => {
      str = func(str);
    });
    
  4. Promisification (looks clean, but has async side-effects):

    let str = 'random text';
    str = await Promise.resolve(str)
      .then(func1)
      .then(func2)
      .then(func3)
      .then(func4);
    

Could you please suggest other fancy ways? I stick to #1, but not sure if it's good enough.

Aucun commentaire:

Enregistrer un commentaire