Convert Function to Variadic

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a function that accepts an array into a variadic function using JavaScript. We will achieve this by creating a closure that collects all inputs into an array-accepting function. By the end of the lab, you will have a better understanding of how to manipulate functions in JavaScript to make them more versatile and adaptable to different use cases.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/async_prog("`Asynchronous Programming`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/data_types -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/arith_ops -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/comp_ops -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/async_prog -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/spread_rest -.-> lab-28214{{"`Convert Function to Variadic`"}} javascript/debugging -.-> lab-28214{{"`Convert Function to Variadic`"}} end

Converting a Function to a Variadic Function

To convert a function that accepts an array into a variadic function, you can follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. Return a closure that collects all inputs into an array-accepting function.

const collectInto =
  (fn) =>
  (...args) =>
    fn(args);
  1. Use the collectInto function to convert a function to a variadic function.
const Pall = collectInto(Promise.all.bind(Promise));
let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = new Promise((resolve) => setTimeout(resolve, 2000, 3));
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)

This will allow you to accept any number of arguments in your function and collect them into an array for further processing.

Summary

Congratulations! You have completed the Convert Function to Variadic lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like