Invoke Functions on Arguments

Beginner

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

Introduction

In this lab, we will explore the functionality of invoking multiple functions on given arguments and returning the results. Specifically, we will create a function that takes in multiple functions and returns a new function that applies each of those functions to the arguments it receives. This will help us better understand the use of Array.prototype.map() and Function.prototype.apply() in JavaScript.

Invoking Functions on Arguments

To execute code using Node.js, open the Terminal/SSH and type node.

To create a function that invokes each provided function with the arguments it receives and returns the results:

  • Use Array.prototype.map() and Function.prototype.apply() to apply each function to the given arguments.
const over =
  (...fns) =>
  (...args) =>
    fns.map((fn) => fn.apply(null, args));

Example:

const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1, 5]

Summary

Congratulations! You have completed the Invoke Functions on Arguments lab. You can practice more labs in LabEx to improve your skills.