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.
Converting a Function to a Variadic Function
To convert a function that accepts an array into a variadic function, you can follow these steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Return a closure that collects all inputs into an array-accepting function.
const collectInto =
(fn) =>
(...args) =>
fn(args);
- Use the
collectIntofunction 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.