Introduction
In this lab, we will explore the use of the overArgs function in JavaScript. The function allows us to transform arguments before passing them to another function. We will learn how to use overArgs to simplify code and increase reusability by creating a new function that invokes an existing function with transformed arguments.
Transform Function Arguments
To transform function arguments, use the overArgs function, which creates a new function that invokes the provided function with its arguments transformed.
- To transform the arguments, use
Array.prototype.map()in combination with the spread operator (...) and pass the transformed arguments tofn.
const overArgs =
(fn, transforms) =>
(...args) =>
fn(...args.map((val, i) => transforms[i](val)));
- To test the
overArgsfunction, create a sample function and an array of transforms, then call the new function with arguments.
const square = (n) => n * n;
const double = (n) => n * 2;
const fn = overArgs((x, y) => [x, y], [square, double]);
fn(9, 3); // [81, 6]
To start practicing coding, open the Terminal/SSH and type node.
Summary
Congratulations! You have completed the Transform Function Arguments lab. You can practice more labs in LabEx to improve your skills.