Transform Function Arguments

JavaScriptJavaScriptBeginner
Practice Now

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

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) 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/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/data_types -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/arith_ops -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/comp_ops -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/array_methods -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/higher_funcs -.-> lab-28666{{"`Transform Function Arguments`"}} javascript/spread_rest -.-> lab-28666{{"`Transform Function Arguments`"}} end

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 to fn.
const overArgs =
  (fn, transforms) =>
  (...args) =>
    fn(...args.map((val, i) => transforms[i](val)));
  • To test the overArgs function, 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.

Other JavaScript Tutorials you may like