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.
Adding Logging to a Function:
4.2.
JavaScript
4.3.
Modifying Return Value:
4.4.
JavaScript
4.5.
Error Handling in Function Execution:
4.6.
JavaScript
4.7.
Performance Monitoring:
5.
Frequently Asked Questions 
5.1.
Can _.wrap() be used with methods of objects?
5.2.
Is the original function still accessible after wrapping?
5.3.
How does _.wrap() compare to subclassing or inheritance?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.wrap() Method

Author Riya Singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Enhancing or modifying the behavior of functions is a common requirement in programming, especially when you need to extend the functionality of existing code without altering it directly. Lodash's _.wrap() method offers a solution by creating a new function that provides a wrapper around the original function. 

Lodash _.wrap() Method

This allows you to execute code before and after the original function call, effectively extending its behavior.

Why This Function is Used

The _.wrap() function is used to add additional behavior to existing functions. It's particularly useful in scenarios such as logging, performance monitoring, input validation, or modifying the return value. By wrapping a function, you can add these features without modifying the original function’s source code, maintaining code integrity and reusability.

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:

 _.wrap(value, wrapper)

Parameters:

  • value (Function): The function to wrap.
     
  • wrapper (Function): The wrapper function.

Return Value: 

(Function) - Returns the new wrapped function.

Examples 

Adding Logging to a Function:

  • JavaScript

JavaScript

var _ = require('lodash');

function multiply(a, b) {

 return a * b;

}

var loggedMultiply = _.wrap(multiply, function(func, ...args) {

 console.log('Multiplying:', args);

 return func(...args);

});

console.log(loggedMultiply(5, 3)); // Logs 'Multiplying: [5, 3]' and outputs 15

Outputs 

15


Demonstrates wrapping a function to add logging capabilities.

Modifying Return Value:

  • JavaScript

JavaScript

function greet(name) {

 return `Hello, ${name}`;

}

var excitedGreet = _.wrap(greet, function(func, ...args) {

 return func(...args) + '!!!';

});

console.log(excitedGreet('Alice'));

 Outputs

 'Hello, Alice!!!'


Shows how to wrap a function to modify its return value.

Error Handling in Function Execution:

  • JavaScript

JavaScript

function riskyOperation() {

 // operation that might throw an error

}

var safeOperation = _.wrap(riskyOperation, function(func) {

 try {

   return func();

 } catch (e) {

   console.error('An error occurred:', e);

 }

});

safeOperation();

// Executes the operation safely with error handling

An example of wrapping a function for added error handling.

Performance Monitoring:

function processData(data) {
  // process the data
}
var monitoredProcess = _.wrap(processData, function(func, ...args) {
  const start = performance.now();
  const result = func(...args);
  const end = performance.now();
  console.log(`Processing took ${end - start}ms`);
  return result;
});
monitoredProcess({ data: 'sample' });


// Executes and logs the processing time

Demonstrates wrapping a function to monitor its performance.

Frequently Asked Questions 

Can _.wrap() be used with methods of objects?

Yes, _.wrap() can be used with object methods, allowing you to extend or modify the behavior of methods without changing the original object.

Is the original function still accessible after wrapping?

The original function is embedded within the wrapped function and is not directly accessible or modifiable from outside the wrapper.

How does _.wrap() compare to subclassing or inheritance?

_.wrap() is a functional programming approach that offers a more flexible and less intrusive alternative to subclassing or inheritance for extending functionality.

Conclusion

Lodash's _.wrap() method is a versatile tool for enhancing or altering the functionality of existing functions. It allows for the execution of additional code before or after the original function, enabling a wide range of applications from error handling to performance monitoring, without altering the original function's core logic.

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.

Previous article
Lodash _.mean() Method
Next article
Lodash _.concat() Method
Live masterclass