Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Swapping Arguments of a Function:
4.2.
JavaScript
4.3.
Reordering Arguments for Compatibility:
4.4.
JavaScript
4.5.
Adjusting Argument Order for Event Handlers:
4.6.
JavaScript
4.7.
Function Adaptation for Array Methods:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
Can _.rearg() handle functions with multiple arguments?
5.2.
How does _.rearg() differ from simply wrapping a function?
5.3.
Is the original function modified by _.rearg()?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.rearg() Method

Author Rahul Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Function argument reordering is a subtle yet powerful technique in programming, particularly useful when interfacing with existing functions or APIs where the argument order isn't ideal. Lodash offers a handy utility for this: the _.rearg() method. This function creates a new function with a reordered argument list, based on the specified indexes.

Lodash _.rearg() Method

It enables the rearrangement of arguments to fit specific requirements without altering the original function.

Why This Function is Used

The _.rearg() function is used to adjust the order of arguments passed to a function. This is especially beneficial when working with callback functions, third-party libraries, or legacy code where you cannot change the function itself but need to alter the argument sequence for compatibility or clarity. It enhances flexibility in function composition and adaptation.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.rearg(func, indexes)

Parameters:

  • func (Function): The function to rearrange arguments for.
     
  • indexes (Array|number): The arranged indexes of arguments.

Return Value: 

(Function) - Returns the new function with rearranged argument order.

Examples 

Swapping Arguments of a Function:

  • JavaScript

JavaScript

var _ = require('lodash');

function divide(a, b) {

 return a / b;

}

var flippedDivide = _.rearg(divide, [1, 0]);

console.log(flippedDivide(2, 10));

Output: 

5 (10 / 2)


Demonstrates swapping the order of arguments for a division function.

Reordering Arguments for Compatibility:

  • JavaScript

JavaScript

function log(level, message, date) {

 console.log(`[${date}] [${level}]: ${message}`);

}

var reorderedLog = _.rearg(log, [2, 0, 1]);

reorderedLog('INFO', 'Log message', new Date().toISOString());

// Rearranges to put the date first, followed by level and message

Shows reordering arguments to fit a specific logging format.

Adjusting Argument Order for Event Handlers:

  • JavaScript

JavaScript

function customEventHandler(arg1, event) {

 console.log(`Event type: ${event.type}, Data: ${arg1}`);

}

var eventHandler = _.rearg(customEventHandler, [1, 0]);

document.addEventListener('click', event => eventHandler('Click data', event));


// Properly orders arguments for the event handler

An example of reordering arguments for an event handler function.

Function Adaptation for Array Methods:

  • JavaScript

JavaScript

function startsWith(prefix, string) {

 return string.startsWith(prefix);

}

var checkStartsWith = _.rearg(startsWith, [1, 0]);

var words = ['apple', 'banana', 'avocado'];

var aWords = _.filter(words, _.partial(checkStartsWith, 'a'));

console.log(aWords);

Output: 

['apple', 'avocado']

Demonstrates reordering a predicate function for use with _.filter.

Frequently Asked Questions

Can _.rearg() handle functions with multiple arguments?

Yes, _.rearg() is designed to handle functions with multiple arguments, allowing you to reorder them as needed.

How does _.rearg() differ from simply wrapping a function?

While you can wrap a function to reorder arguments, _.rearg() provides a more concise and declarative way to achieve this, especially for simple reordering needs.

Is the original function modified by _.rearg()?

No, _.rearg() creates a new function without altering the original function. The original function remains available with its original argument order.

Conclusion

Lodash's _.rearg() method is a practical tool for rearranging the order of arguments passed to a function. It offers a flexible way to adapt and interface with existing functions, enhancing compatibility and easing integration with different codebases or APIs.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass